package com.useeinfo.oa.modules.inspection.biz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.useeinfo.framework.extend.biz.CrudBiz;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.func.file.FileUtils;
import com.useeinfo.framework.sugar.tools.*;
import com.useeinfo.oa.common.config.ConstantKeyFilePath;
import com.useeinfo.oa.common.enums.ResultEnums;
import com.useeinfo.oa.common.utils.CommonUtils;
import com.useeinfo.oa.common.utils.NumberUtil;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.*;
import com.useeinfo.oa.modules.base.entity.*;
import com.useeinfo.oa.modules.base.enums.AuditTypeEnum;
import com.useeinfo.oa.modules.base.enums.MessageTypeEnum;
import com.useeinfo.oa.modules.base.enums.ResourceTypeEnum;
import com.useeinfo.oa.modules.base.vo.MessageVO;
import com.useeinfo.oa.modules.inspection.dao.InspectionOrderDao;
import com.useeinfo.oa.modules.inspection.entity.*;
import com.useeinfo.oa.modules.inspection.enums.*;
import com.useeinfo.oa.modules.base.biz.PlanMessageSendBiz;
import com.useeinfo.oa.modules.base.entity.PlanMessageSend;
import com.useeinfo.oa.modules.maintaining.entity.*;
import com.useeinfo.oa.modules.maintaining.enums.OrderOperationEnum;
import com.useeinfo.oa.modules.maintaining.enums.OrderStatusEnum;
import com.useeinfo.oa.modules.repair.biz.RepairLevelBiz;
import com.useeinfo.oa.modules.repair.biz.RepairOrderBiz;
import com.useeinfo.oa.modules.repair.entity.RepairLevel;
import com.useeinfo.oa.modules.repair.entity.RepairOrder;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.biz.SystemAuthorityBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.biz.UserDeviceBiz;
import com.useeinfo.oa.modules.security.entity.SystemAuthority;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.entity.UserDevice;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import com.useeinfo.oa.modules.threadUtil.ThreadUtils;
import com.xiaoleilu.hutool.util.CollectionUtil;
import javafx.util.StringConverter;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.annotations.Check;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @auther: bin.liu
 * @Date: 2019/1/14 9:15
 * @Description: 巡检工单service
 */
@Service("inspectionOrderBiz")
public class InspectionOrderBiz extends CrudBiz<InspectionOrderDao, InspectionOrder> {

    @Autowired
    private HttpServletRequest httpServletRequest;

    @Autowired
    private InspectionFocusBiz inspectionFocusBiz;
    @Autowired
    private FacilityInspectionSnapBiz facilityInspectionSnapBiz;
    @Autowired
    private ResourceBiz resourceBiz;
    @Autowired
    private AuditFlowBiz auditFlowBiz;
    @Autowired
    private OrganizationBiz organizationBiz;
    @Autowired
    private InspectionTechnologyBiz inspectionTechnologyBiz;
    @Autowired
    private InspectionDataBiz inspectionDataBiz;
    @Autowired
    private InspectionOrderWorkContentBiz inspectionOrderWorkContentBiz;
    @Autowired
    private InspectionOrderLogBiz inspectionOrderLogBiz;
    @Autowired
    private InsApplyOrderBiz insApplyOrderBiz;
    @Autowired
    private InsAuditOrderBiz insAuditOrderBiz;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private DictInfoBiz dictInfoBiz;
    @Autowired
    private SystemUserBiz systemUserBiz;
    @Autowired
    private PositionBiz positionBiz;
    @Autowired
    private InspectionExecuteTimeBiz inspectionExecuteTimeBiz;
    @Autowired
    private FacilityInspectionBiz facilityInspectionBiz;
    @Autowired
    private InspectionWorkingHoursBiz inspectionWorkingHoursBiz;
    @Autowired
    private SystemAuthorityBiz systemAuthorityBiz;
    @Autowired
    private InspectionPartnerBiz inspectionPartnerBiz;
    @Autowired
    private InspectionWorkContentRemarkBiz inspectionWorkContentRemarkBiz;
    @Autowired
    private SystemUserOrganizationBiz systemUserOrganizationBiz;
    @Autowired
    private InspectionToRepairBiz inspectionToRepairBiz;
    @Autowired
    private FacilityBiz facilityBiz;
    @Autowired
    private FacilityCatBiz facilityCatBiz;
    @Autowired
    private EnterpriseBiz enterpriseBiz;
    @Autowired
    private PlanMessageSendBiz planMessageSendBiz;
    @Autowired
    private InspectionWorkLogBiz inspectionWorkLogBiz;
    @Autowired
    private ApplicationModuleBiz applicationModuleBiz;
    @Autowired
    private RepairLevelBiz repairLevelBiz;
    @Autowired
    private RepairOrderBiz repairOrderBiz;

    public List<Object> getYearPlan(String id) {
        return dao.getYearPlan(id);
    }

    public String dashBoardInfo(String enterpriseId, String status, String date) {
        return dao.dashBoardInfo(enterpriseId, status, date);
    }

    public JSONArray getbetween(String enterpriseId, String start, String end, int type, boolean completed) {
        return dao.getbetween(enterpriseId, start, end, type, completed);
    }

    public List<Object> getOrganizationReceiveNum(String organizationId, String start, String end) {
        return dao.getOrganizationReceiveNum(organizationId, start, end);
    }

    public String inspectionReportNum(String enterpriseId, String status) {
        return dao.inspectionReportNum(enterpriseId, status);
    }

    /**
     * 巡检工单  关注/取消关注
     *
     * @param inspectionOrderId
     * @param type
     * @return
     */
    public ResultDto focus(String inspectionOrderId, Boolean type) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || enterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

        // 关注
        if (type) {
            InspectionFocus inspectionFocus = new InspectionFocus();
            inspectionFocus.setEnterprise(enterprise);
            inspectionFocus.setSystemUser(systemUser);
            inspectionFocus.setInspectionOrder(dao.findModel(StringConverters.null2Long(inspectionOrderId)));
            inspectionFocusBiz.addOrUpdate(inspectionFocus);
        } else {
            // 取消关注
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("systemUserId", StringConverters.null2String(systemUser.getId()));
            queryParam.getSqlMap().put("inspectionOrderId", inspectionOrderId);
            queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
            List<InspectionFocus> inspectionFocusList = inspectionFocusBiz.findList(queryParam);
            for (InspectionFocus inspectionFocus : inspectionFocusList) {
                inspectionFocusBiz.delete(inspectionFocus.getId());
            }
        }
        return ResultUtil.success();
    }


    /**
     * 工单是否关注了
     *
     * @param inspectionOrderId
     * @param systemUser
     * @param enterprise
     * @return
     */
    public Boolean isFocus(String inspectionOrderId, SystemUser systemUser, Enterprise enterprise) {
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("inspectionOrderId", inspectionOrderId);
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
        queryParam.getSqlMap().put("systemUserId", StringConverters.null2String(systemUser.getId()));
        List<InspectionFocus> inspectionFocusList = inspectionFocusBiz.findList(queryParam);
        if (CollectionUtils.isEmpty(inspectionFocusList)) {
            return false;
        }
        return true;
    }

    /**
     * 按计划产生维保工单接口
     *
     * @param plannerInspection 工单计划
     * @param startTime         工单开始时间
     * @param endTime           工单结束时间
     * @return
     */
    public ResultDto makeInspectionOrder(PlannerInspection plannerInspection, Date startTime, Date endTime, int type, InspectionExecuteTime inspectionExecuteTime) {
        if (null == startTime || null == endTime || null == plannerInspection) {
            logger.info("未传入正确生成维保工单的参数");
            return ResultUtil.error("未传入正确生成维保工单的参数");
        }
        /*********改变状态，下次不再生成该工单**************/
        if (type == 1) {
            inspectionExecuteTime.setStatus(1);
            inspectionExecuteTimeBiz.addOrUpdate(inspectionExecuteTime);
        }
        /*********生成工单基础信息start**************/
        List<Long> ids = new ArrayList<>();
        InspectionOrder inspectionOrder = new InspectionOrder();
        inspectionOrder.setCreateDate(new Date());
        inspectionOrder.setPlannerInspection(plannerInspection);
        inspectionOrder.setOrderCode(plannerInspection.getEnterprise() == null ? StringConverters.formatTime("yyyyMMdd", new Date()) +
                "-" + StringConverters.getRandomNum(6) : plannerInspection.getEnterprise().getId() + "-" + StringConverters.formatTime("yyyyMMdd", new Date()) +
                "-" + StringConverters.getRandomNum(6));
        inspectionOrder.setEnterprise(plannerInspection.getEnterprise());
        inspectionOrder.setStartDateTime(startTime);
        inspectionOrder.setEndDateTime(endTime);
        inspectionOrder.setDelayRealTime(endTime);
//        inspectionOrder.setAssign(plannerInspection.getAssign());//TODO
        Set<Position> positionSet = new HashSet<>();
        for (Position position : plannerInspection.getAssignPositions()) {
            ids.add(StringConverters.null2Long(position.getId()));
            positionSet.add(position);
        }
        inspectionOrder.setAssignPositions(positionSet);
        Set<SystemUser> systemUserSet = new HashSet<>();
        for (SystemUser systemUser : plannerInspection.getAssignUsers()) {
            ids.add(StringConverters.null2Long(systemUser.getId()));
            systemUserSet.add(systemUser);
        }
        inspectionOrder.setAssignUsers(systemUserSet);
        inspectionOrder.setOrderAssignTypeEnum(plannerInspection.getInsOrderAssignTypeEnum());
        inspectionOrder.setOrderName(plannerInspection.getName());
        inspectionOrder.setCreateUser(plannerInspection.getCreateUser());
        inspectionOrder.setAuditCompleteID(plannerInspection.getAuditComplete() == null ? null : plannerInspection.getAuditComplete().getId());
        inspectionOrder.setCompleteFlow(plannerInspection.getCompleteFlow());
        inspectionOrder.setDelayFlowID(plannerInspection.getAuditDelay() == null ? null : plannerInspection.getAuditDelay().getId());
        inspectionOrder.setDelayFlow(plannerInspection.getDelayFlow());

        inspectionOrder.setCancelFlowID(plannerInspection.getAuditCancel() == null ? null : plannerInspection.getAuditCancel().getId());
        inspectionOrder.setCancelFlow(plannerInspection.getCancelFlow());

        inspectionOrder.setRemindTime(plannerInspection.getRemindTime());
        inspectionOrder.setRemindDateTime(StringConverters.beforeDate(startTime, plannerInspection.getRemindTime()));
        inspectionOrder.setRequired(plannerInspection.getRequired());
        inspectionOrder.setType(plannerInspection.getType());
        inspectionOrder.setDegree(plannerInspection.getDegree());
        inspectionOrder.setPoints(plannerInspection.getPoints());
        inspectionOrder.setSafeInstruction(plannerInspection.isSafeInstruction());
        inspectionOrder.setResource(plannerInspection.getResource());
        inspectionOrder.setBelongOganization(plannerInspection.getOrganization());
        dao.add(inspectionOrder);
        /*********生成工单基础信息end**************/

        /*********生成工单——设备和工艺——工作内容信息start**************/
        QueryParam queryParam = new QueryParam(-1, -1);
        queryParam.getSqlMap().put("plannerId", plannerInspection.getId().toString());
        queryParam.getSqlMap().put("inspectionId", "is not null");
        List<FacilityInspection> facilityInspectionSet = facilityInspectionBiz.findList(queryParam); /*plannerOrder.getFacilityInspections();*/
        for (FacilityInspection facilityInspection : facilityInspectionSet) {
            FacilityInspectionSnap facilityInspectionSnap = new FacilityInspectionSnap();
            facilityInspectionSnap.setCreateDate(new Date());
            facilityInspectionSnap.setInspectionOrder(inspectionOrder);
            facilityInspectionSnap.setOrderCode(inspectionOrder.getOrderCode());
            facilityInspectionSnap.setAreaId(facilityInspection.getAreaId());
            facilityInspectionSnap.setAreaName(facilityInspection.getAreaName());
            facilityInspectionSnap.setFacilityCatId(facilityInspection.getFacilityCatId());
            facilityInspectionSnap.setFacilityCatName(facilityInspection.getFacilityCatName());
            FacilityCat rootCat = facilityCatBiz.findRootCat(facilityInspection.getFacilityCatId());
            if (rootCat != null) {
                facilityInspectionSnap.setRootCatId(rootCat.getId());
            }
            facilityInspectionSnap.setFacilityCode(facilityInspection.getFacilityCode());
            facilityInspectionSnap.setFacilityGroupCode(facilityInspection.getFacilityGroupCode());
            facilityInspectionSnap.setFacilityGroupId(facilityInspection.getFacilityGroupId());
            facilityInspectionSnap.setFacilityGroupName(facilityInspection.getFacilityGroupName());
            facilityInspectionSnap.setFacilityId(facilityInspection.getFacilityId());
            facilityInspectionSnap.setFacilityName(facilityInspection.getFacilityName());
            facilityInspectionSnap.setInspectionId(facilityInspection.getInspectionId());
            facilityInspectionSnap.setInspectionName(facilityInspection.getInspectionName());
            facilityInspectionSnap.setQRCode(facilityInspection.getQRCode());
            facilityInspectionSnap.setSpec(facilityInspection.getSpec());
            facilityInspectionSnap.setTempVal(facilityInspection.getTempVal());
            facilityInspectionSnapBiz.addOrUpdate(facilityInspectionSnap);

            /**解析工艺内容start***/
            JSONArray jsonArray = JSONArray.parseArray(facilityInspection.getInspectionDataContent());
            for (Object object : jsonArray) {
                JSONObject jsonObject = (JSONObject) object;
                InspectionOrderWorkContent inspectionOrderWorkContent = new InspectionOrderWorkContent();
                inspectionOrderWorkContent.setCreateDate(new Date());
                inspectionOrderWorkContent.setFacilityInspectionSnap(facilityInspectionSnap);
                inspectionOrderWorkContent.setName(jsonObject.getString("name"));
                inspectionOrderWorkContent.setMaxNumber(jsonObject.getDouble("maxNumber"));
                inspectionOrderWorkContent.setMinNumber(jsonObject.getDouble("minNumber"));
                inspectionOrderWorkContent.setPhoto(StringConverters.null2Boolean(jsonObject.getBoolean("photo")));
                inspectionOrderWorkContent.setApplication_scenarios_id(jsonObject.getLong("applicationScenariosId"));
                inspectionOrderWorkContent.setApplication_scenarios_name(jsonObject.getString("applicationScenariosName"));
                inspectionOrderWorkContent.setContent(jsonObject.getString("content"));
                inspectionOrderWorkContent.setResourceIds(jsonObject.getString("resourceIds"));
                inspectionOrderWorkContent.setUnit(jsonObject.getString("unit"));
                inspectionOrderWorkContent.setCategory(jsonObject.getString("category"));
                inspectionOrderWorkContent.setInputTypeEnum(InputTypeEnum.valueOf(jsonObject.getString("inputTypeEnumCode")));
                inspectionOrderWorkContentBiz.addOrUpdate(inspectionOrderWorkContent);
            }
            /**解析工艺内容end***/
        }
        /*********生成工单——设备和工艺——工作内容信息end**************/


        //更新预计工时
        inspectionOrder.setExpectWorkingHours(updateExpectWorkingHours(inspectionOrder.getId() + ""));
//        inspectionOrder.setAbnormal(true);
        this.addOrUpdate(inspectionOrder);

        //消息推送 TODO
        String content = "巡检单:" + inspectionOrder.getOrderCode() + "等待接单!";
        ids = dao.inspectionOrderUserIds(inspectionOrder, inspectionOrder.getEnterprise(), ids);
        planMessageSendBiz.senMsg(inspectionOrder.getId(), "inspection", inspectionOrder.getEnterprise(), ids, content);
        //操作日志
        InspectionOrderLog inspectionOrderLog = new InspectionOrderLog();
        inspectionOrderLog.setInspectionOrder(inspectionOrder);
        inspectionOrderLog.setEnterprise(plannerInspection.getEnterprise());
        inspectionOrderLog.setSystemUser(plannerInspection.getCreateUser());
        inspectionOrderLog.setUserName(plannerInspection.getCreateUser() == null ? "" : plannerInspection.getCreateUser().getUserName());
        String detail = plannerInspection.getCreateUser().getUserName() + "在" + DateTimeUtils.formatDateToStringWithTime(new Date()) + ","
                + InsOrderOperationEnum.CREATE_ORDER.getName() + "，操作工单名称为：" + inspectionOrder.getOrderName() + ",编号为：" + inspectionOrder.getId();
        inspectionOrderLog.setDetail(detail);
        inspectionOrderLog.setOrderOperationEnum(InsOrderOperationEnum.CREATE_ORDER);
        return ResultUtil.success();
    }

    /**
     * 保存工单
     *
     * @return
     */
    public ResultDto save(InspectionOrder inspectionOrder,
                          MultipartFile pic1,
                          String sImg1,
                          String end,
                          List<String> selectCompleteAuditFlowIds,
                          List<String> selectDelayAuditFlowIds,
                          List<String> selectCancelAuditFlowIds,
                          List<String> selectOrganizationIds,
                          HttpServletRequest request) {
        //先判断是否有绑定设备,并且设备是否都绑定了工艺
        if (StringUtils.isBlank(inspectionOrder.getSerial())) {
            return ResultUtil.error("参数异常");
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("serial", inspectionOrder.getSerial());
        List<FacilityInspectionSnap> facilityInspectionSnapList = facilityInspectionSnapBiz.findList(queryParam);
        if (CollectionUtils.isEmpty(facilityInspectionSnapList)) {
            return ResultUtil.error("请绑定设备");
        }
        for (FacilityInspectionSnap facilityInspectionSnap : facilityInspectionSnapList) {
            if (facilityInspectionSnap.getInspectionId() == null) {
                return ResultUtil.error("请绑定工艺");
            }
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        inspectionOrder.setEnterprise(enterprise);
        inspectionOrder.setCreateUser(systemUser);
        inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.WAIT_TAKING);//未接单
        inspectionOrder.setOrderCode(enterprise == null ? StringConverters.formatTime("yyyyMMdd", new Date()) +
                "-" + StringConverters.getRandomNum(6) : enterprise.getId() + "-" + StringConverters.formatTime("yyyyMMdd", new Date()) +
                "-" + StringConverters.getRandomNum(6));
        //上传资料操作
        if ("1".equals(sImg1)) {
            //首先删除之前的关联资料文件
            inspectionOrder.setResource(null);
            //如果有新资料文件 再存新资料文件
            String savePath1 = FileUtils.fileUpload(pic1, ConstantKeyFilePath.MAINTAINING_SAFETY_PDF_DIR, ConstantKeyFilePath.MAINTAINING_SAFETY_PDF_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
            if (StringUtils.isNotEmpty(savePath1)) {
                Resource resource = new Resource();
                String resourceName = pic1.getOriginalFilename();
                resource.setPath(savePath1);
                resource.setResourceTypeEnum(ResourceTypeEnum.PDF);
                resource.setResourceName(resourceName);
                resourceBiz.addOrUpdate(resource);
                inspectionOrder.setResource(resource);
            }
        }
        Date startDate = DateTimeUtils.parse("yyyy-MM-dd HH:mm", DateTimeUtils.format(new Date(), "yyyy-MM-dd HH:mm"));
        inspectionOrder.setStartDateTime(startDate);
        inspectionOrder.setStartDateTime(startDate);
        inspectionOrder.setEndDateTime(DateTimeUtils.parse("yyyy-MM-dd HH:mm", end));
        inspectionOrder.setDelayRealTime(inspectionOrder.getEndDateTime());
        inspectionOrder.setRemindDateTime(StringConverters.beforeDate(startDate, inspectionOrder.getRemindTime()));
        if (CollectionUtils.isNotEmpty(selectCompleteAuditFlowIds)) {
            AuditFlow completeFlow = auditFlowBiz.findModel(StringConverters.ToLong(selectCompleteAuditFlowIds.get(0)));
            inspectionOrder.setCompleteFlow(completeFlow.getFlow());
            inspectionOrder.setAuditCompleteID(completeFlow.getId());
        } else {
            //默认审批流
            if (auditFlowBiz.getDefaultFlow("complete", enterprise, 3) != null) {
                inspectionOrder.setCompleteFlow(auditFlowBiz.getDefaultFlow("complete", enterprise, 3).getFlow());
                inspectionOrder.setAuditCompleteID(auditFlowBiz.getDefaultFlow("complete", enterprise, 3).getId());
            }
        }
        if (CollectionUtils.isNotEmpty(selectDelayAuditFlowIds)) {
            AuditFlow delayFlow = auditFlowBiz.findModel(StringConverters.ToLong(selectDelayAuditFlowIds.get(0)));
            inspectionOrder.setDelayFlow(delayFlow.getFlow());
            inspectionOrder.setDelayFlowID(delayFlow.getId());
        } else {
            //默认审批流

            if (auditFlowBiz.getDefaultFlow("delay", enterprise, 3) != null) {
                inspectionOrder.setDelayFlow(auditFlowBiz.getDefaultFlow("delay", enterprise, 3).getFlow());
                inspectionOrder.setDelayFlowID(auditFlowBiz.getDefaultFlow("delay", enterprise, 3).getId());
            }
        }

        if (CollectionUtils.isNotEmpty(selectCancelAuditFlowIds)) {
            AuditFlow cancelFlow = auditFlowBiz.findModel(StringConverters.ToLong(selectCancelAuditFlowIds.get(0)));
            inspectionOrder.setCancelFlow(cancelFlow.getFlow());
            inspectionOrder.setCancelFlowID(cancelFlow.getId());
        } else {
            //默认审批流
            if (auditFlowBiz.getDefaultFlow("cancel", enterprise, 3) != null) {
                inspectionOrder.setCancelFlow(auditFlowBiz.getDefaultFlow("cancel", enterprise, 3).getFlow());
                inspectionOrder.setCancelFlowID(auditFlowBiz.getDefaultFlow("cancel", enterprise, 3).getId());
            }
        }

        if (CollectionUtils.isNotEmpty(selectOrganizationIds)) {
            inspectionOrder.setBelongOganization(organizationBiz.findModel(StringConverters.ToLong(selectOrganizationIds.get(0))));
        }
        inspectionOrder.setOrderType(true);
        if (inspectionOrder.getId() == null) {
            dao.add(inspectionOrder);
        } else {
            dao.update(inspectionOrder);
        }
        //给临时设备工艺信息添加id(正式绑定)
        for (FacilityInspectionSnap facilityInspectionSnap : facilityInspectionSnapList) {
            facilityInspectionSnap.setInspectionOrder(inspectionOrder);
            facilityInspectionSnapBiz.addOrUpdate(facilityInspectionSnap);
        }
        //增加InspectionOrderWorkContent
        QueryParam queryParam1 = new QueryParam();
        queryParam1.getSqlMap().put("inspectionOrderId", inspectionOrder.getId() + "");
        queryParam1.getSqlMap().put("serial", inspectionOrder.getSerial());
        List<FacilityInspectionSnap> facilityInspectionSnapList1 = facilityInspectionSnapBiz.findList(queryParam1);
        if (CollectionUtils.isNotEmpty(facilityInspectionSnapList1)) {
            for (FacilityInspectionSnap facilityInspectionSnap : facilityInspectionSnapList1) {
                InspectionTechnology inspectionTechnology = inspectionTechnologyBiz.findModel(facilityInspectionSnap.getInspectionId());
                if (inspectionTechnology != null) {
                    QueryParam queryParam2 = new QueryParam();
                    queryParam2.getSqlMap().put("inspectionTechnologyId", inspectionTechnology.getId() + "");
                    List<InspectionData> inspectionDataList = inspectionDataBiz.findList(queryParam2);
                    for (InspectionData inspectionData : inspectionDataList) {
                        InspectionOrderWorkContent inspectionOrderWorkContent = new InspectionOrderWorkContent();
                        inspectionOrderWorkContent.setFacilityInspectionSnap(facilityInspectionSnap);
                        inspectionOrderWorkContent.setName(inspectionData.getName());
                        inspectionOrderWorkContent.setApplication_scenarios_id(inspectionData.getDictInfo().getId());
                        inspectionOrderWorkContent.setApplication_scenarios_name(inspectionData.getDictInfo().getPropertyName());
                        inspectionOrderWorkContent.setInputTypeEnum(inspectionData.getInputTypeEnum());
                        inspectionOrderWorkContent.setMaxNumber(inspectionData.getMaxNumber());
                        inspectionOrderWorkContent.setMinNumber(inspectionData.getMinNumber());
                        inspectionOrderWorkContent.setUnit(inspectionData.getUnit());
                        inspectionOrderWorkContent.setPhoto(inspectionData.isPhoto());
                        inspectionOrderWorkContent.setContent(inspectionData.getContent());
                        Set<Resource> pdfResource = inspectionData.getEnclosure();
                        if (pdfResource != null && pdfResource.size() > 0) {
                            Resource resource = pdfResource.iterator().next();
                            if (resource != null) {
                                inspectionOrderWorkContent.setResourceIds(resource.getId() + "");
                            }
                        }
                        inspectionOrderWorkContentBiz.addOrUpdate(inspectionOrderWorkContent);
                    }
                }
            }
        }
        //更新预计工时
        inspectionOrder.setExpectWorkingHours(updateExpectWorkingHours(inspectionOrder.getId() + ""));
//        inspectionOrder.setAbnormal(true);
        this.addOrUpdate(inspectionOrder);
        //消息推送 TODO
        String content = "巡检单:" + inspectionOrder.getOrderCode() + "等待接单!";
        List<Long> ids = new ArrayList<>();
        ids = dao.inspectionOrderUserIds(inspectionOrder, inspectionOrder.getEnterprise(), ids);
        planMessageSendBiz.senMsg(inspectionOrder.getId(), "inspection", inspectionOrder.getEnterprise(), ids, content);
        //操作日志
        inspectionOrderLogBiz.saveInspectionOrderLog(inspectionOrder, InsOrderOperationEnum.CREATE_ORDER, request);
        return ResultUtil.success();
    }

    /**
     * PC端批量审批工单
     *
     * @param ids
     * @param type
     * @param reason
     * @param request
     * @return
     */
    public ResultDto auditOrder(String ids, String type, String reason, String score, String remark, HttpServletRequest request) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(ids);
        if (type.equals("1")) {
            batchAudit(ids, score, remark, systemUser, request);
        } else {
            jsonArray.forEach(x -> {
                audit(x.toString(), type.equals("0") ? "0" : "-1", reason, systemUser, request);
            });
        }

        return ResultUtil.success();
    }

    /**
     * 批量审核接口
     *
     * @param orderIds
     * @param score
     * @param remark
     * @param systemUser
     * @param request
     * @return
     */
    public ResultDto batchAudit(String orderIds, String score, String remark, SystemUser systemUser, HttpServletRequest request) {
        JSONArray jsonArray = JSONArray.parseArray(orderIds);
        for (Object object : jsonArray) {
            InspectionOrder inspectionOrder = dao.findModel(StringConverters.null2Long(object));
            if (null != inspectionOrder) {
//                if (inspectionOrder.isAbnormal()) {
//                    throw new RuntimeException("工单号为：" + inspectionOrder.getOrderCode() + "的工单异常，不可批量审核");
//                }
//                if (!inspectionOrder.getOrderStatusEnum().getCode().equals("IN_AUDITING")) {
//                    throw new RuntimeException("工单号为：" + inspectionOrder.getOrderCode() + "不可进行此操作");
//                }
                if (inspectionOrder.isAuditLast()) {//工单终审状态
                    int level = inspectionOrder.getLevel();
                    inspectionOrder.setLevel(0);
                    inspectionOrder.setAuditing(false);//审核完结  置为初始
                    inspectionOrder.setPosition(null);
                    inspectionOrder.setAuditSystemUser(null);
                    inspectionOrder.setOrganization(null);
                    inspectionOrder.setAuditLast(false);
                    inspectionOrder.setAuditFirst(false);
                    inspectionOrder.setScore(StringConverters.null2Int(score));
                    if(inspectionOrder.getOrderStatusEnum().getCode().equals("IN_AUDITING")){
                        inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.COMPLETED);
                    }else if(inspectionOrder.getDelay()){
                        inspectionOrder.setEndDateTime(inspectionOrder.getDelayTime());
                    }
                    dao.update(inspectionOrder);
                    /*****添加审核日志*****/
                    insAuditOrderBiz.saveOrUpdate(inspectionOrder, systemUser, true, remark, AuditTypeEnum.COMPLETE, level);
                    //操作日志
                    inspectionOrderLogBiz.saveInspectionOrderLog(inspectionOrder, InsOrderOperationEnum.AUDIT, request);
                } else {//工单非终审状态
                    audit(inspectionOrder.getId().toString(), "0", null, systemUser, request);
                }
            }
        }
        return ResultUtil.success();
    }

    /**
     * 审核工单接口
     *
     * @param orderId 工单ID
     * @param result  结果 0通过 -1 不通过
     * @param remark  留言
     * @return
     */
    public ResultDto audit(String orderId, String result, String remark, SystemUser systemUser, HttpServletRequest request) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (null == enterprise) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        InspectionOrder inspectionOrder = dao.findModel(StringConverters.null2Long(orderId));
        if (null == inspectionOrder) {
            return ResultUtil.error("该工单不存在");
        }
        int level = inspectionOrder.getLevel();
        if (!inspectionOrder.getCancel() && !inspectionOrder.getDelay() && !inspectionOrder.isAuditing()) {
            return ResultUtil.error("该工单不在审核状态中");
        }
        String content = "";
        // 获取 当前审批管理申请记录
        InsApplyOrder insApplyOrder = inspectionOrder.getInsApplyOrder();

        if (null != insApplyOrder && !inspectionOrder.isAuditing()) {
            // 完成审核不改变申请
            if (StringConverters.null2String(result).equals("-1")) {
                insApplyOrder.setEffective(false);
            }
            insApplyOrder.setLevel(level);
            insApplyOrderBiz.update(insApplyOrder);
        }
        List<Long> ids=new ArrayList<>();//用于消息推送储存userId

        inspectionOrder.setAuditFirst(false);//去除初审标签
        inspectionOrder.setPosition(null);//清空当前节点人员以及岗位数据
        inspectionOrder.setAuditSystemUser(null);
        inspectionOrder.setOrganization(null);
        if (inspectionOrder.getDelay()) {
            //延期审批
            if (null == inspectionOrder.getDelayFlowID()) {//未配置审批流
                inspectionOrder.setDelay(false);
                inspectionOrder.setLevel(0);
                inspectionOrder.setDelayRealTime(inspectionOrder.getDelayTime() == null ? inspectionOrder.getDelayRealTime() : inspectionOrder.getDelayTime());
            } else {
                JSONArray jsonArray = JSONArray.parseArray(inspectionOrder.getDelayFlow());
                if (0 == jsonArray.size()) {//配置的审批流  没有配置节点
                    inspectionOrder.setLevel(0);
                    inspectionOrder.setDelay(false);
                    inspectionOrder.setDelayRealTime(inspectionOrder.getDelayTime() == null ? inspectionOrder.getDelayRealTime() : inspectionOrder.getDelayTime());
                }
                if (level == jsonArray.size()&&StringConverters.null2String(result).equals("0")) {//终极审批  审核完结
                    content = "巡检单:" + inspectionOrder.getOrderCode() + "已完成审核";
                    inspectionOrder.setLevel(0);
                    inspectionOrder.setDelay(false);//审核完结  置为初始
                    inspectionOrder.setAuditSystemUser(null);
                    inspectionOrder.setPosition(null);
                    inspectionOrder.setOrganization(null);
                    inspectionOrder.setEndDateTime(inspectionOrder.getDelayTime());
                    inspectionOrder.setAuditLast(false); //去除终审标签
                    if (StringConverters.null2String(result).equals("0")) {//审核通过
                        inspectionOrder.setDelayRealTime(inspectionOrder.getDelayTime() == null ? inspectionOrder.getDelayRealTime() : inspectionOrder.getDelayTime());
                    }
                } else {
                    if (StringConverters.null2String(result).equals("0")) {//审核通过
                        content = "巡检单:" + inspectionOrder.getOrderCode() + ", " + systemUser.getUserName() + "延期审核通过";
                        if (level == 0) {
                            level = 1;
                        }
                        if (jsonArray.size() - level == 1) { //用于判断是不是最后一级审核
                            inspectionOrder.setAuditLast(true);
                        }
                        JSONObject jsonObject = (JSONObject) jsonArray.get(level);
                        inspectionOrder.setOrganization(organizationBiz.findModel(StringConverters.null2Long(jsonObject.getString("organizationId"))));
                        inspectionOrder.setLevel(level + 1);
                        String auditType = jsonObject.getString("nodeTypeEnum");
                        if (StringConverters.null2String(auditType).equals("USER")) {//审批类型  用户或者岗位
                            SystemUser relationUser=systemUserBiz.findModel(StringConverters.null2Long(jsonObject.getString("relationId")));
                            inspectionOrder.setAuditSystemUser(relationUser);
                            ids.add(relationUser.getId());
                        } else {
                            inspectionOrder.setPosition(positionBiz.findModel(StringConverters.null2Long(jsonObject.getString("relationId"))));
                            ids.addAll(systemUserBiz.getUserIdsByPosition(jsonObject.getString("relationId"),jsonObject.getString("organizationId"),enterprise.getId().toString()));
                        }
                    } else {//审核不通过
                        content = "巡检单:" + inspectionOrder.getOrderCode() + ", " + systemUser.getUserName() + "延期审核驳回";
                        inspectionOrder.setLevel(0);
                        inspectionOrder.setDelay(false);//审核完结  置为初始
                        inspectionOrder.setAuditSystemUser(null);
                        inspectionOrder.setPosition(null);
                        inspectionOrder.setOrganization(null);
                        inspectionOrder.setAuditLast(false);
                    }
                }
            }
            dao.update(inspectionOrder);
            /*****添加审核日志*****/
            insAuditOrderBiz.saveOrUpdate(inspectionOrder, systemUser, StringConverters.null2String(result).equals("0"), remark, AuditTypeEnum.DELAY, level);
        } else if (inspectionOrder.getCancel()) {
            //取消审批

            if (null == inspectionOrder.getCancelFlowID()) {//未配置审批流
                inspectionOrder.setLevel(0);
                inspectionOrder.setCancel(false);
                inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.CANCEL);
            } else {
                JSONArray jsonArray = JSONArray.parseArray(inspectionOrder.getDelayFlow());
                if (jsonArray == null || 0 == jsonArray.size()) {//配置的审批流  没有配置节点
                    inspectionOrder.setLevel(0);
                    inspectionOrder.setCancel(false);
                    inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.CANCEL);
                }
                if (jsonArray != null && level == jsonArray.size()&&StringConverters.null2String(result).equals("0")) {//终极审批  审核完结
                    content = "巡检单:" + inspectionOrder.getOrderCode() + "已完成审核";
                    inspectionOrder.setLevel(0);
                    inspectionOrder.setCancel(false);//审核完结  置为初始
                    inspectionOrder.setPosition(null);
                    inspectionOrder.setAuditSystemUser(null);
                    inspectionOrder.setOrganization(null);
                    inspectionOrder.setAuditLast(false);
                    if (StringConverters.null2String(result).equals("0")) {//审核通过
                        inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.CANCEL);
                    }
                } else {
                    content = "巡检单:" + inspectionOrder.getOrderCode() + ", " + systemUser.getUserName() + "取消审核通过";
                    if (StringConverters.null2String(result).equals("0")) {//审核通过
                        if (level == 0) {
                            level = 1;
                        }
                        if (jsonArray.size() - level == 1) { //用于判断是不是最后一级审核  添加终审标签
                            inspectionOrder.setAuditLast(true);
                        }
                        JSONObject jsonObject = (JSONObject) jsonArray.get(level);
                        inspectionOrder.setLevel(level + 1);
                        String auditType = jsonObject.getString("nodeTypeEnum");
                        inspectionOrder.setOrganization(organizationBiz.findModel(StringConverters.null2Long(jsonObject.getString("organizationId"))));
                        if (StringConverters.null2String(auditType).equals("USER")) {//审批类型  用户或者岗位
                            SystemUser relationUser=systemUserBiz.findModel(StringConverters.null2Long(jsonObject.getString("relationId")));
                            inspectionOrder.setAuditSystemUser(relationUser);
                            ids.add(relationUser.getId());
                        } else {
                            inspectionOrder.setPosition(positionBiz.findModel(StringConverters.null2Long(jsonObject.getString("relationId"))));
                            ids.addAll(systemUserBiz.getUserIdsByPosition(jsonObject.getString("relationId"),jsonObject.getString("organizationId"),enterprise.getId().toString()));
                        }
                    } else {//审核不通过
                        content = "巡检单:" + inspectionOrder.getOrderCode() + ", " + inspectionOrder.getLevel() + "取消审核驳回";
                        inspectionOrder.setLevel(0);
                        inspectionOrder.setCancel(false);//审核完结  置为初始
                        inspectionOrder.setAuditSystemUser(null);
                        inspectionOrder.setPosition(null);
                        inspectionOrder.setOrganization(null);
                        inspectionOrder.setAuditLast(false);

                    }
                }
            }
            dao.update(inspectionOrder);

            /*****添加审核日志*****/
            insAuditOrderBiz.saveOrUpdate(inspectionOrder, systemUser, StringConverters.null2String(result).equals("0"), remark, AuditTypeEnum.CANCEL, level);
        } else if (inspectionOrder.isAuditing()) {
            //完成审批
            if (null == inspectionOrder.getAuditCompleteID()) {//未配置审批流
                inspectionOrder.setLevel(0);
                inspectionOrder.setAuditing(false);
                inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.COMPLETED);
            } else {
                JSONArray jsonArray = JSONArray.parseArray(inspectionOrder.getCompleteFlow());
                if (0 == jsonArray.size()) {//配置的审批流  没有配置节点
                    inspectionOrder.setLevel(0);
                    inspectionOrder.setAuditing(false);
                    inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.COMPLETED);
                }
                if (level == jsonArray.size()) {//终极审批  审核完结
                    content = "巡检工单:" + inspectionOrder.getOrderCode() + "已完成审核";
                    inspectionOrder.setLevel(0);
                    inspectionOrder.setAuditing(false);//审核完结  置为初始
                    inspectionOrder.setAuditSystemUser(null);
                    inspectionOrder.setPosition(null);
                    inspectionOrder.setOrganization(null);
                    inspectionOrder.setAuditLast(false);
                    if (StringConverters.null2String(result).equals("0")) {//审核通过
                        inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.COMPLETED);
                    } else {
                        inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.WAIT_PRESENCE);
                    }
                } else {
                    content = "巡检工单:" + inspectionOrder.getOrderCode() + ", " + systemUser.getUserName() + "审核通过";
                    if (StringConverters.null2String(result).equals("0")) {
                        //审核通过
                        if (level == 0) {
                            level = 1;
                        }
                        if (jsonArray.size() - level == 1) { //用于判断是不是最后一级审核  添加终审标签
                            inspectionOrder.setAuditLast(true);
                        }
                        JSONObject jsonObject = (JSONObject) jsonArray.get(level);
                        inspectionOrder.setLevel(level + 1);
                        inspectionOrder.setOrganization(organizationBiz.findModel(StringConverters.null2Long(jsonObject.getString("organizationId"))));
                        String auditType = jsonObject.getString("nodeTypeEnum");
                        if (StringConverters.null2String(auditType).equals("USER")) {//审批类型  用户或者岗位
                            SystemUser relationUser=systemUserBiz.findModel(StringConverters.null2Long(jsonObject.getString("relationId")));
                            inspectionOrder.setAuditSystemUser(relationUser);
                            ids.add(relationUser.getId());
                        } else {
                            inspectionOrder.setPosition(positionBiz.findModel(StringConverters.null2Long(jsonObject.getString("relationId"))));
                            ids.addAll(systemUserBiz.getUserIdsByPosition(jsonObject.getString("relationId"),jsonObject.getString("organizationId"),enterprise.getId().toString()));
                        }
                    } else {
                        //审核不通过
                        content = "巡检单:" + inspectionOrder.getOrderCode() + ", " +systemUser.getUserName() + "审核驳回";
                        inspectionOrder.setLevel(0);
                        inspectionOrder.setAuditing(false);//审核完结  置为初始
                        inspectionOrder.setPosition(null);
                        inspectionOrder.setAuditSystemUser(null);
                        inspectionOrder.setOrganization(null);
                        inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.WAIT_PRESENCE);
                        inspectionOrder.setAuditLast(false);
                    }
                }
            }
            dao.update(inspectionOrder);
            if(ids.contains(inspectionOrder.getReceiveUser().getId())){
                ids.add(inspectionOrder.getReceiveUser().getId());
            }
            //推送消息
            if (ids.size() > 0) {
                planMessageSendBiz.senMsg(inspectionOrder.getId(), "inspection", enterprise, ids, content);
            }

            /*****添加审核日志*****/
            insAuditOrderBiz.saveOrUpdate(inspectionOrder, systemUser, StringConverters.null2String(result).equals("0"), remark, AuditTypeEnum.COMPLETE, level);
            //操作日志
            inspectionOrderLogBiz.saveInspectionOrderLog(inspectionOrder, result.equals("0") ? InsOrderOperationEnum.AUDIT : InsOrderOperationEnum.REJECT, request);
        }
        return ResultUtil.success();
    }

    /**
     * 指派人员
     *
     * @param assignIds
     * @param orderId
     * @return
     */
    public ResultDto assignUsers(String assignIds, String orderId, HttpServletRequest request) {
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(assignIds);
        InspectionOrder inspectionOrder = dao.findModel(StringConverters.null2Long(orderId));
        Set<SystemUser> systemUsers = inspectionOrder.getAssignUsers();
        List<Long> ids = new ArrayList<>();
        if (systemUsers == null) {
            systemUsers = new HashSet<>();
        }
        for (Object id : jsonArray) {
            SystemUser systemUser = systemUserBiz.findModel(StringConverters.null2Long(id));
            if (systemUser != null) {
                systemUsers.add(systemUser);
                ids.add(systemUser.getId());
            }
        }
        inspectionOrder.setAssign(Boolean.TRUE);
        inspectionOrder.setOrderAssignTypeEnum(InsOrderAssignTypeEnum.USER);
        inspectionOrder.setAssignUsers(systemUsers);
        dao.update(inspectionOrder);
        //消息推送TODO 推送给新的指派人员
        String content = "巡检单:" + inspectionOrder.getOrderCode() + "等待接单!";
        planMessageSendBiz.senMsg(inspectionOrder.getId(), "inspection", inspectionOrder.getEnterprise(), ids, content);


        //操作日志
        inspectionOrderLogBiz.saveInspectionOrderLog(inspectionOrder, InsOrderOperationEnum.ASSIGN_USER, request);
        return ResultUtil.success();
    }

    /**
     * 指派岗位
     *
     * @param assignIds
     * @param orderId
     * @return
     */
    public ResultDto assignPositions(String assignIds, String orderId, HttpServletRequest request) {
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(assignIds);
        InspectionOrder inspectionOrder = dao.findModel(StringConverters.null2Long(orderId));
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        Set<Position> positions = inspectionOrder.getAssignPositions();
        List<Long> ids = new ArrayList<>();
        if (positions == null) {
            positions = new HashSet<>();
        }
        for (Object id : jsonArray) {
            Position position = positionBiz.findModel(StringConverters.null2Long(id));
            if (positions != null) {
                positions.add(position);
                ids = systemUserBiz.getUserIdsByPosition(id.toString(),null, enterprise.getId() + "");
            }
        }
        inspectionOrder.setAssign(Boolean.TRUE);
        inspectionOrder.setOrderAssignTypeEnum(InsOrderAssignTypeEnum.POSITION);
        inspectionOrder.setAssignPositions(positions);
        dao.update(inspectionOrder);
        //消息推送 TODO 推送给新的岗位人员
        String content = "巡检单:" + inspectionOrder.getOrderCode() + "等待接单!";
        planMessageSendBiz.senMsg(inspectionOrder.getId(), "inspection", inspectionOrder.getEnterprise(), ids, content);

        //操作日志
        inspectionOrderLogBiz.saveInspectionOrderLog(inspectionOrder, InsOrderOperationEnum.ASSIGN_POSITION, request);
        return ResultUtil.success();
    }


    /**
     * 设置截止日期
     *
     * @param id
     * @param endDate
     * @return
     */
    public ResultDto saveAssignDate(String id, String endDate, HttpServletRequest request) {
        InspectionOrder inspectionOrder = dao.findModel(StringConverters.null2Long(id));
        if (inspectionOrder.getOrderStatusEnum().getCode().equals("WAIT_TAKING") || inspectionOrder.getOrderStatusEnum().getCode().equals("WAIT_PULISHING")) {
            //在未接单之前都可以设置截止日期
            inspectionOrder.setEndDateTime(StringConverters.ToDatePattern(endDate, "yyyy-MM-dd HH:mm"));
            inspectionOrder.setDelayRealTime(StringConverters.ToDatePattern(endDate, "yyyy-MM-dd HH:mm"));
            dao.update(inspectionOrder);
            //操作日志
            inspectionOrderLogBiz.saveInspectionOrderLog(inspectionOrder, InsOrderOperationEnum.END_DATE, request);
        }
        return ResultUtil.success();
    }

    /**
     * 计算工单完成百分比(以及工单是否异常)
     */
    public void updatePercent(String inspectionOrderId) {
        InspectionOrder inspectionOrder = this.findModel(StringConverters.ToLong(inspectionOrderId));
        if (inspectionOrder == null) {
            return;
        }
        inspectionOrder.setMark(true);
        //百分比
        int totalCount = 0;
        int finishCount = 0;
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("inspectionOrderId", inspectionOrderId);
        List<FacilityInspectionSnap> facilityInspectionSnapList = facilityInspectionSnapBiz.findList(queryParam);
        boolean flagSnap=false;
        if (CollectionUtils.isNotEmpty(facilityInspectionSnapList)) {
            //循环设备
            for (FacilityInspectionSnap facilityInspectionSnap : facilityInspectionSnapList) {
                JSONArray applicationArray = new JSONArray();
                QueryParam queryParam1 = new QueryParam();
                queryParam1.getSqlMap().put("facilityInspectionSnapId", facilityInspectionSnap.getId() + "");
                List<InspectionOrderWorkContent> inspectionOrderWorkContentList = inspectionOrderWorkContentBiz.findList(queryParam1);
                if (CollectionUtils.isNotEmpty(inspectionOrderWorkContentList)) {
                    //循环工作内容
                    for (InspectionOrderWorkContent inspectionOrderWorkContent : inspectionOrderWorkContentList) {
                        //计算完成数
                        totalCount += 1;
                        if (StringUtils.isNotBlank(inspectionOrderWorkContent.getResult())) {
                            finishCount += 1;
                        }
                        //判断是否异常
                        if (inspectionOrderWorkContent.getAbnormal() != null && inspectionOrderWorkContent.getAbnormal()) {
                            flagSnap=true;
                        }
                        //查询有几个运行场景
                        JSONObject applicationJson = new JSONObject();
                        applicationJson.put("applicationId", inspectionOrderWorkContent.getApplication_scenarios_id());
                        applicationJson.put("applicationName", inspectionOrderWorkContent.getApplication_scenarios_name());
                        if (!applicationArray.contains(applicationJson)) {
                            applicationArray.add(applicationJson);
                        }
                    }
                        facilityInspectionSnap.setAbnormal(flagSnap);
                }
                facilityInspectionSnapBiz.addOrUpdate(facilityInspectionSnap);

                //循环运行场景 如果单个运行场景的工作内容都是已完成 则认为该设备为已完成
                for (int i = 0; i < applicationArray.size(); i++) {
                    JSONObject json = applicationArray.getJSONObject(i);
                    Long applicationId = json.getLong("applicationId");
                    QueryParam queryParam2 = new QueryParam();
                    queryParam2.getSqlMap().put("facilityInspectionSnapId", facilityInspectionSnap.getId() + "");
                    queryParam2.getSqlMap().put("applicationId", applicationId + "");
                    List<InspectionOrderWorkContent> workContentList2 = inspectionOrderWorkContentBiz.findList(queryParam2);
                    if (CollectionUtils.isNotEmpty(workContentList2)) {
                        boolean applicationCompleted = true;
                        for (InspectionOrderWorkContent workContent : workContentList2) {
                            if (StringUtils.isBlank(workContent.getResult())) {
                                applicationCompleted = false;
                                break;
                            } else {
                                //即使有结果内容 但如果强制拍照的没拍照 也算未完成
                                if (workContent.getPhoto() && (workContent.getContentPhoto() == null || workContent.getContentPhoto().size() == 0)) {
                                    applicationCompleted = false;
                                    break;
                                }
                            }
                        }
                        if (applicationCompleted) {
                            //只要其中一个循环内容全不为空，即设备其中一个应用场景已经全部完成 则认为该设备已完成
                            facilityInspectionSnap.setCompleted(true);
                            //同时认为该设备正常
                            facilityInspectionSnap.setAbnormal(false);
                            facilityInspectionSnapBiz.addOrUpdate(facilityInspectionSnap);
                            break;
                        }
                    }
                }
            }
        }
        int percent = 0;
        if (totalCount != 0) {
            percent = (finishCount * 100) / totalCount;
        }
        inspectionOrder.setPercent(percent);
        boolean flag = false;
        //查询工单是否异常
        for (FacilityInspectionSnap facilityInspectionSnap : facilityInspectionSnapList) {
            if (facilityInspectionSnap.isAbnormal()) {
                flag = true;
            }
        }
//        inspectionOrder.setAbnormal(flag);

        this.addOrUpdate(inspectionOrder);
    }

    /**
     * app保存工单接口
     *
     * @param request
     * @return
     */
    public ResultDto saveOrder(String name, String degree, String endTime, String required, String remindTime,
                               String assignUser, String assignPosition, String completeAuditId, String delayAuditId, String cancelAuditId,
                               String inspectionData, HttpServletRequest request) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if (enterprise == null || systemUser == null) {
            return ResultUtil.error("登陆过期，请重新登陆");
        }
        List<Long> ids = new ArrayList<>();
        List<SystemUser> assignUsers = new ArrayList<>();
        InspectionOrder inspectionOrder = new InspectionOrder();
        String serial = StringConverters.getRandomString(10);
        inspectionOrder.setEnterprise(enterprise);
        inspectionOrder.setCreateUser(systemUser);
        inspectionOrder.setSerial(serial);
        inspectionOrder.setOrderCode(enterprise == null ? StringConverters.formatTime("yyyyMMdd", new Date()) +
                "-" + StringConverters.getRandomNum(6) : enterprise.getId() + "-" + StringConverters.formatTime("yyyyMMdd", new Date()) +
                "-" + StringConverters.getRandomNum(6));
        inspectionOrder.setOrderName(name);
        inspectionOrder.setDegree(degree);
        inspectionOrder.setOrderType(true);
        inspectionOrder.setStartDateTime(new Date());
        inspectionOrder.setEndDateTime(StringConverters.formatDate(endTime, "yyyy-MM-dd HH:mm"));
        inspectionOrder.setDelayRealTime(inspectionOrder.getEndDateTime());
        inspectionOrder.setRequired(required);
        inspectionOrder.setRemindTime(StringConverters.null2Int(remindTime));
        inspectionOrder.setRemindDateTime(StringConverters.beforeDate(inspectionOrder.getStartDateTime(), inspectionOrder.getRemindTime()));
        //指派数据
        net.sf.json.JSONArray userArray = net.sf.json.JSONArray.fromObject(assignUser);
        net.sf.json.JSONArray positionArray = net.sf.json.JSONArray.fromObject(assignPosition);
        if (userArray.size() != 0 && positionArray.size() != 0) {
            return ResultUtil.error("指派只能选择一种类型");
        } else if (userArray.size() != 0) {//指派人员
            inspectionOrder.setOrderAssignTypeEnum(InsOrderAssignTypeEnum.USER);
            Set<SystemUser> systemUserSet = new HashSet<>();
            userArray.forEach(x -> {
                systemUserSet.add(systemUserBiz.findModel(StringConverters.null2Long(x)));
                ids.add(StringConverters.null2Long(x));
            });
            inspectionOrder.setAssignUsers(systemUserSet);
            inspectionOrder.setAssign(true);
        } else if (positionArray.size() != 0) {//指派岗位
            inspectionOrder.setOrderAssignTypeEnum(InsOrderAssignTypeEnum.POSITION);
            Set<Position> positionHashSet = new HashSet<>();
            positionArray.forEach(x -> {
                positionHashSet.add(positionBiz.findModel(StringConverters.null2Long(x)));
                ids.add(StringConverters.null2Long(x));
            });
            inspectionOrder.setAssign(true);
            inspectionOrder.setAssignPositions(positionHashSet);
        }
        AuditFlow completeFlow = auditFlowBiz.findModel(StringConverters.null2Long(completeAuditId));//完成审批流
        if (completeFlow == null) {
            completeFlow = auditFlowBiz.getDefaultFlow("complete", enterprise, 3);
        }
        inspectionOrder.setCompleteFlow(completeFlow != null ? completeFlow.getFlow() : "");
        inspectionOrder.setAuditCompleteID(completeFlow != null ? completeFlow.getId() : null);

        AuditFlow delayFlow = auditFlowBiz.findModel(StringConverters.null2Long(delayAuditId));//延期审批流
        if (delayFlow == null) {
            delayFlow = auditFlowBiz.getDefaultFlow("delay", enterprise, 3);
        }
        inspectionOrder.setDelayFlow(delayFlow != null ? delayFlow.getFlow() : "");
        inspectionOrder.setDelayFlowID(delayFlow != null ? delayFlow.getId() : null);

        AuditFlow cancelFlow = auditFlowBiz.findModel(StringConverters.null2Long(cancelAuditId));//取消审批流
        if (cancelFlow == null) {
            cancelFlow = auditFlowBiz.getDefaultFlow("cancel", enterprise, 3);
        }
        inspectionOrder.setCancelFlow(cancelFlow != null ? cancelFlow.getFlow() : "");
        inspectionOrder.setCancelFlowID(cancelFlow != null ? cancelFlow.getId() : null);
        dao.add(inspectionOrder);
        //设备工艺数据
        net.sf.json.JSONArray inspectionArray = net.sf.json.JSONArray.fromObject(inspectionData);
        if (inspectionArray.size() == 0) {
            return ResultUtil.success("请添加设备");
        }
        inspectionArray.forEach(x -> {
            String facilityId = net.sf.json.JSONObject.fromObject(x).getString("facilityId");
            String inspectionId = net.sf.json.JSONObject.fromObject(x).getString("inspectionId");
            facilityInspectionSnapBiz.saveFacilityInspectionSnap(inspectionOrder.getId() + "", facilityId, inspectionId, serial);

        });
        inspectionOrderLogBiz.saveInspectionOrderLog(inspectionOrder, InsOrderOperationEnum.CREATE_ORDER, request);//log日志

        //更新预计工时
        inspectionOrder.setExpectWorkingHours(updateExpectWorkingHours(inspectionOrder.getId() + ""));
//        inspectionOrder.setAbnormal(true);
        this.addOrUpdate(inspectionOrder);


        //消息推送
        List<SystemUser> systemUsers1 = dao.inspectionOrderUser(inspectionOrder, enterprise, ids);
        String content = "有新的巡检单!请接单";
        String takingAuthority = "ROLE_ENTERPRISE_INSPECTION_ORDER_TAKING";
        for (SystemUser user : systemUsers1) {
            if (systemAuthorityBiz.hasAuthAuthority(takingAuthority, user.getId(), enterprise.getId())) {
                PlanMessageSend planMessageSend = new PlanMessageSend();
                planMessageSend.setContent(content);
                planMessageSend.setEnterprise(enterprise);
                planMessageSend.setSendDate(inspectionOrder.getRemindDateTime());
                planMessageSend.setMessageTypeEnum(MessageTypeEnum.INSPECTION);
                planMessageSend.setOrderCode(inspectionOrder.getOrderCode());
                planMessageSend.setSendToUser(user);
                planMessageSendBiz.addOrUpdate(planMessageSend);
            }
        }

        return ResultUtil.success();

    }

    /**
     * 工单详情
     *
     * @param id
     * @return
     */
    public ResultDto detail(String id) {

        JSONArray buttons = new JSONArray();
        JSONArray unfinished = new JSONArray();
        JSONArray finished = new JSONArray();

        InspectionOrder inspectionOrder = dao.findModel(StringConverters.null2Long(id));

        if (null == inspectionOrder) {
            return ResultUtil.error("该工单不存在");
        }
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (null == systemUser) {
            return ResultUtil.error("用户未登录");
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == enterprise) {
            return ResultUtil.error("企业信息有误");
        }


        QueryParam inspectionParam = new QueryParam();
        inspectionParam.getSqlMap().put("inspectionOrderId", StringConverters.null2String(inspectionOrder.getId()));
        List<FacilityInspectionSnap> FacilityInspectionSnaps = facilityInspectionSnapBiz.findList(inspectionParam);
        JSONObject jsonObject = inspectionOrder.toJSONObject();
        //工时计算
        net.sf.json.JSONObject workingTime = net.sf.json.JSONObject.fromObject(nowWorkHours(id).getData());
        if (inspectionOrder.getOrderStatusEnum().getCode().equals("UNFINISHED")) {
            jsonObject.put("totalWorkingHours", workingTime.get("totalHours"));//总工时
            jsonObject.put("workingHours", workingTime.get("receiveHours"));//我的工时
        }
        jsonObject.put("beforeHours", inspectionOrder.getWorkingHours());//退回重修前的工时
        jsonObject.put("beforeTotalHours",  inspectionOrder.getTotalWorkingHours());//退回重修前的总工时
        for (FacilityInspectionSnap facilityInspectionSnap : FacilityInspectionSnaps) {
            JSONObject inspectionObject = new JSONObject();
            inspectionObject.put("facilityName", StringConverters.null2String(facilityInspectionSnap.getFacilityName()));
            inspectionObject.put("facilityCode", StringConverters.null2String(facilityInspectionSnap.getFacilityCode()));
            inspectionObject.put("facilityId", facilityInspectionSnap.getFacilityId());
            inspectionObject.put("applicationId", facilityInspectionSnap.getApplicationScenariosId() == null ? "" : facilityInspectionSnap.getApplicationScenariosId());
            inspectionObject.put("inspectionName", StringConverters.null2String(facilityInspectionSnap.getInspectionName()));
            inspectionObject.put("spec", StringConverters.null2String(facilityInspectionSnap.getSpec()));
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("facilityInspectionSnapId", StringConverters.null2String(facilityInspectionSnap.getId()));
            List<InspectionOrderWorkContent> inspectionOrderWorkContents = inspectionOrderWorkContentBiz.findList(queryParam);
            JSONArray contentArray = new JSONArray();
            JSONArray applicationArray = new JSONArray();
            for (InspectionOrderWorkContent inspection : inspectionOrderWorkContents) {
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("applicationName", inspection.getApplication_scenarios_name());
                jsonObject1.put("applicationId", inspection.getApplication_scenarios_id());
                if (!applicationArray.contains(jsonObject1)) {
                    applicationArray.add(jsonObject1);
                }
            }
            inspectionObject.put("snapId", facilityInspectionSnap.getId());
            inspectionObject.put("applicationArray", applicationArray);
            for (InspectionOrderWorkContent inspection : inspectionOrderWorkContents) {
                JSONObject contentObject = new JSONObject();
                contentObject.put("inputTypeEnum", StringConverters.null2String(inspection.getInputTypeEnum().getCode()));
                if ("COMPLETE_TYPE".equals(inspection.getInputTypeEnum().getCode()) || "STATUS_TYPE".equals(inspection.getInputTypeEnum().getCode())) {
                    String[] names = inspection.getInputTypeEnum().getName().split("、");
                    JSONArray nameArray = new JSONArray();
                    JSONObject nameS = new JSONObject();
                    nameS.put("content", "尚未选择");
                    nameS.put("isNormal", false);
                    nameArray.add(nameS);
                    for (String o : names) {
                        JSONObject nameStatus = new JSONObject();
                        if ("异常".equals(o) || "无此项目".equals(o) || "需处理（不能运转）".equals(o)) {
                            nameStatus.put("isNormal", false);
                        } else {
                            nameStatus.put("isNormal", true);
                        }
                        nameStatus.put("content", o);
                        nameArray.add(nameStatus);
                    }
//                    nameArray.addAll(Arrays.asList(names));
                    contentObject.put("inputType", nameArray);
                } else {
                    contentObject.put("inputType", StringConverters.null2String(inspection.getInputTypeEnum().getName()));
                }
                contentObject.put("contentId", StringConverters.null2Long(inspection.getId()));
                contentObject.put("unit", StringConverters.null2String(inspection.getUnit()));
                contentObject.put("applicationId", StringConverters.null2Long(inspection.getApplication_scenarios_id()));
                contentObject.put("applicationName", StringConverters.null2String(inspection.getApplication_scenarios_name()));
                contentObject.put("photo", StringConverters.null2Boolean(inspection.getPhoto()));
                contentObject.put("maxNumber", StringConverters.null2Double(inspection.getMaxNumber()));
                contentObject.put("minNumber", StringConverters.null2Double(inspection.getMinNumber()));
                contentObject.put("abnormal", StringConverters.null2Boolean(inspection.getAbnormal()));
                contentObject.put("name", StringConverters.null2String(inspection.getName()));
                contentObject.put("content", StringConverters.null2String(inspection.getContent()));
                JSONArray array = new JSONArray();
                if (StringUtils.isNotBlank(inspection.getContent())) {
                    array = JSONArray.parseArray(inspection.getContent());
                }
                contentObject.put("contentArray", array);
                contentObject.put("category", StringConverters.null2String(inspection.getCategory()));
                contentObject.put("result", StringConverters.null2String(inspection.getResult()));
                JSONArray photoArray = new JSONArray();
                if (inspection.getContentPhoto() != null) {
                    List<Resource> contentPhotos = new ArrayList<>(inspection.getContentPhoto());
                    contentPhotos.sort((o1, o2) -> o1.getId() < o2.getId() ? -1 : 1);
                    if (CollectionUtils.isNotEmpty(contentPhotos)) {
                        for (Resource resource : contentPhotos) {
                            photoArray.add(resource.getPath());
                        }
                    }
                }
                contentObject.put("photos", photoArray);
                String path = "";
                if (StringUtils.isNotBlank(inspection.getResourceIds())) {
                    Resource model = resourceBiz.findModel(StringConverters.null2Long(inspection.getResourceIds()));
                    if (model != null) {
                        path = model.getPath();
                    }

                }
                contentObject.put("resources", path);

                QueryParam contentParam = new QueryParam();
                contentParam.getSqlMap().put("contentId", StringConverters.null2String(inspection.getId()));
                List<InspectionWorkContentRemark> inspectionWorkContentRemarks = inspectionWorkContentRemarkBiz.findList(contentParam);
                if (CollectionUtils.isNotEmpty(inspectionWorkContentRemarks)) {
                    contentObject.put("hasRemark", 1);
                } else {
                    contentObject.put("hasRemark", 0);
                }

                contentArray.add(contentObject);
            }
            inspectionObject.put("contents", contentArray);
            if (facilityInspectionSnap.isCompleted()) {
                finished.add(inspectionObject);
            } else {
                unfinished.add(inspectionObject);
            }
        }

        jsonObject.put("finished", finished);
        jsonObject.put("unfinished", unfinished);

        systemUser = systemUserBiz.findModel(StringConverters.null2Long(systemUser.getId()));
        Set<SystemUserOrganization> systemUserOrganizationSet = systemUser.getSystemUserOrganizationSet();
        boolean leader = false;
        Organization organization = null;
        if (CollectionUtils.isNotEmpty(systemUserOrganizationSet)) {
            //所属部门
            leader = systemUserOrganizationSet.iterator().next().isLeader();
            organization = systemUserOrganizationSet.iterator().next().getOrganization();
        }


        String takingAuthorityName = "ROLE_ENTERPRISE_INSPECTION_ORDER_TAKING";
        String auditAuthorityName = "ROLE_ENTERPRISE_INSPECTION_ORDER_AUDIT";
        String assignAuthorityName = "ROLE_ENTERPRISE_INSPECTION_PLANNER_ORDER_ASSIGN";
        // 批量转单权限code
        String transfersHorityName = "ROLE_ENTERPRISE_INSPECTION_BATCH_TRANSFER";


        String code = inspectionOrder.getOrderStatusEnum().getCode();

        if (("WAIT_PRESENCE".equals(code) || "UNFINISHED".equals(code)) && (inspectionOrder.getCancel() || inspectionOrder.getDelay())) {
            //判断工单取消和延期按钮
            if (systemAuthorityBiz.hasAuthAuthority(auditAuthorityName, systemUser.getId(), enterprise.getId())) {
                if (organization != null) {
                    if (inspectionOrder.getAuditSystemUser() != null || inspectionOrder.getPosition() != null) {
                        if ((inspectionOrder.getOrganization() == organization && inspectionOrder.getAuditSystemUser() == systemUser)) {
                            buttons.add("passButton");
                            buttons.add("rejectButton");
                        } else if (inspectionOrder.getOrganization() == organization && inspectionOrder.getPosition() == systemUser.getPosition(enterprise, systemUser.getPositionSet())) {
                            buttons.add("passButton");
                            buttons.add("rejectButton");
                        }
                    }
                }
            }
        }

        if ("WAIT_TAKING".equals(code)) {
            if (systemAuthorityBiz.hasAuthAuthority(assignAuthorityName, systemUser.getId(), enterprise.getId())) {
                buttons.add("assignButton");
            }
            if (systemAuthorityBiz.hasAuthAuthority(takingAuthorityName, systemUser.getId(), enterprise.getId())) {
                //指定接单人的，需要判断我发起的工单有没有指派
                Position position=systemUser.getPosition(enterprise,systemUser.getPositionSet());//获取当前企业下的职位
                if(inspectionOrder.getAssign()&&(inspectionOrder.getAssignUsers().contains(systemUser)||inspectionOrder.getAssignPositions().contains(position))){
                    buttons.add("takingButton");
                } else if (!inspectionOrder.getAssign()) {
                    // 如果不是指派的，但有接单权限，给按钮
                    buttons.add("takingButton");
                }
            }
        } else if ("WAIT_PRESENCE".equals(code)) {
            if (inspectionOrder.getReceiveUser() == systemUser) {
                buttons.add("presenceButton");
                if (!inspectionOrder.getDelay() && !inspectionOrder.getCancel()) {
                    buttons.add("cancelButton");
                    buttons.add("delayButton");
                }
                // 如果这个人有批量转单的权限，就给他添加转单的权限判断等操作，如果他没有批量转单的权限，就不给他有转单权限
                // 转单权限
                if (systemAuthorityBiz.hasAuthAuthority(transfersHorityName, systemUser.getId(), enterprise.getId())) {
                    if (!inspectionOrder.getCancel()) {
                        buttons.add("transferButton");
                    }
                }
            }
        } else if ("UNFINISHED".equals(code)) {
            if (inspectionOrder.getReceiveUser() == systemUser) {
                if (!inspectionOrder.getDelay() && !inspectionOrder.getCancel()) {
                    buttons.add("cancelButton");
                    buttons.add("delayButton");
                }
                if (systemAuthorityBiz.hasAuthAuthority(transfersHorityName, systemUser.getId(), enterprise.getId())) {
                    if (!inspectionOrder.getCancel()) {
                        buttons.add("transferButton");
                    }
                }
                buttons.add("saveButton");
                buttons.add("submitButton");
            }
        } else if ("REJECTED".equals(code)) {
            if (inspectionOrder.getReceiveUser() == systemUser) {
                buttons.add("presenceButton");
            }
        } else if ("IN_AUDITING".equals(code)) {
            if (systemAuthorityBiz.hasAuthAuthority(auditAuthorityName, systemUser.getId(), enterprise.getId())) {
                if (organization != null) {
                    if (inspectionOrder.getAuditSystemUser() != null || inspectionOrder.getPosition() != null) {
                        if ((inspectionOrder.getOrganization() == organization && inspectionOrder.getAuditSystemUser() == systemUser)) {
                            buttons.add("passButton");
                            buttons.add("rejectButton");
                        } else if (inspectionOrder.getOrganization() == organization && inspectionOrder.getPosition() == systemUser.getPosition(enterprise, systemUser.getPositionSet())) {
                            buttons.add("passButton");
                            buttons.add("rejectButton");
                        }
                    }
                }
            }

        }

        QueryParam queryParam1 = new QueryParam();
        queryParam1.getSqlMap().put("inspectionOrderId", StringConverters.null2String(inspectionOrder.getId()));
        queryParam1.getSqlMap().put("applyType", "CANCEL");
        queryParam1.setSqlOrder(" order by createDate ");
        List<InsApplyOrder> insApplyOrders = insApplyOrderBiz.findList(queryParam1);
        if (CollectionUtils.isNotEmpty(insApplyOrders)) {
            jsonObject.put("cancelReason", insApplyOrders.get(insApplyOrders.size() - 1).getReason());
            jsonObject.put("cancelType", insApplyOrders.get(insApplyOrders.size() - 1).getDictInfo() == null ? "" : insApplyOrders.get(insApplyOrders.size() - 1).getDictInfo().getPropertyName());
        }

        queryParam1.getSqlMap().put("applyType", "DELAY");
        insApplyOrders = insApplyOrderBiz.findList(queryParam1);
        if (CollectionUtils.isNotEmpty(insApplyOrders)) {
            jsonObject.put("delayReason", insApplyOrders.get(insApplyOrders.size() - 1).getReason());
            jsonObject.put("delayType", insApplyOrders.get(insApplyOrders.size() - 1).getDictInfo() == null ? "" : insApplyOrders.get(insApplyOrders.size() - 1).getDictInfo().getPropertyName());

        }

        JSONArray completeArray = new JSONArray();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("inspectionOrderId", StringConverters.null2String(inspectionOrder.getId()));
        queryParam.getSqlMap().put("auditType", "COMPLETE");
        queryParam.setSqlOrder("order by createDate ");
        List<InsAuditOrder> auditOrders = insAuditOrderBiz.findList(queryParam);
        for (InsAuditOrder insAuditOrder : auditOrders) {
            completeArray.add(insAuditOrder.toJSONObject());
        }

        JSONArray delayArray = new JSONArray();
        queryParam.getSqlMap().put("auditType", "DELAY");
        auditOrders = insAuditOrderBiz.findList(queryParam);
        for (InsAuditOrder auditOrder : auditOrders) {
            delayArray.add(auditOrder.toJSONObject());
        }

        JSONArray cancelArray = new JSONArray();
        queryParam.getSqlMap().put("auditType", "CANCEL");
        auditOrders = insAuditOrderBiz.findList(queryParam);
        for (InsAuditOrder auditOrder : auditOrders) {
            cancelArray.add(auditOrder.toJSONObject());
        }

        QueryParam partnerParam = new QueryParam();
        partnerParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
        partnerParam.getSqlMap().put("inspectionOrderId", StringConverters.null2String(inspectionOrder.getId()));
        List<InspectionPartner> partners = inspectionPartnerBiz.findList(partnerParam);
        JSONArray partnerArray = new JSONArray();
        for (InspectionPartner inspectionPartner : partners) {
            JSONObject partnerObject = new JSONObject();
            partnerObject.put("deleteStatus", inspectionPartner.isDeleteStatus());
            partnerObject.put("partnerId", inspectionPartner.getId());
            partnerObject.put("userId", inspectionPartner.getPartner().getId());
            partnerObject.put("userName", inspectionPartner.getPartner().getUserName());
            partnerObject.put("workingHours", inspectionPartner.getWorkingHours());
            partnerArray.add(partnerObject);
        }
        jsonObject.put("partner", partnerArray);
        jsonObject.put("completeArray", completeArray);
        jsonObject.put("delayArray", delayArray);
        jsonObject.put("cancelArray", cancelArray);
        // 按钮
        jsonObject.put("buttons", buttons);
        jsonObject.put("isFocus", isFocus(id, systemUser, enterprise));
        jsonObject.put("systemUserId", systemUser.getId());


        return ResultUtil.success(jsonObject);
    }


    /**
     * 指派岗位
     *
     * @param assignIds
     * @param orderId
     * @return
     */
    public ResultDto assignPositionsApp(String assignIds, String orderId, HttpServletRequest request) {
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(assignIds);
        InspectionOrder inspectionOrder = dao.findModel(StringConverters.null2Long(orderId));
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        Set<Position> positions = new HashSet<>();
        List<Long> ids = new ArrayList<>();
        for (Object id : jsonArray) {
            Position position = positionBiz.findModel(StringConverters.null2Long(id));
            if (positions != null) {
                positions.add(position);
                ids = systemUserBiz.getUserIdsByPosition(id.toString(),null, enterprise.getId() + "");

            }
        }
        inspectionOrder.setAssign(Boolean.TRUE);
        inspectionOrder.setOrderAssignTypeEnum(InsOrderAssignTypeEnum.POSITION);
        inspectionOrder.setAssignPositions(positions);
        dao.update(inspectionOrder);
        //消息推送 TODO 推送给新的岗位人员
        String content = "巡检单:" + inspectionOrder.getOrderCode() + "等待接单!";
        planMessageSendBiz.senMsg(inspectionOrder.getId(), "inspection", inspectionOrder.getEnterprise(), ids, content);
        //操作日志
        inspectionOrderLogBiz.saveInspectionOrderLog(inspectionOrder, InsOrderOperationEnum.ASSIGN_POSITION, request);
        return ResultUtil.success();
    }

    /**
     * 指派人员APP
     *
     * @param assignIds
     * @param orderId
     * @return
     */
    public ResultDto assignUsersApp(String assignIds, String orderId, HttpServletRequest request) {
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(assignIds);
        InspectionOrder inspectionOrder = dao.findModel(StringConverters.null2Long(orderId));
        Set<SystemUser> systemUsers = new HashSet<>();
        List<Long> ids = new ArrayList<>();

        for (Object id : jsonArray) {
            SystemUser systemUser = systemUserBiz.findModel(StringConverters.null2Long(id));
            if (systemUser != null) {
                systemUsers.add(systemUser);
                ids.add(systemUser.getId());
            }
        }
        inspectionOrder.setAssign(Boolean.TRUE);
        inspectionOrder.setOrderAssignTypeEnum(InsOrderAssignTypeEnum.USER);
        inspectionOrder.setAssignUsers(systemUsers);
        dao.update(inspectionOrder);
        //消息推送 TODO 推送给新的指派人员
        String content = "巡检单:" + inspectionOrder.getOrderCode() + "等待接单!";
        planMessageSendBiz.senMsg(inspectionOrder.getId(), "inspection", inspectionOrder.getEnterprise(), ids, content);

        //操作日志
        inspectionOrderLogBiz.saveInspectionOrderLog(inspectionOrder, InsOrderOperationEnum.ASSIGN_USER, request);
        return ResultUtil.success();
    }

    /**
     * 工单转单接口
     *
     * @param orderIds
     * @param userId
     * @return
     */
    public ResultDto setReceiver(String orderIds, String userId) {
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(request);
        SystemUser systemUser = systemUserBiz.findModel(StringConverters.null2Long(userId));
        if (null == systemUser) {
            return ResultUtil.error("请选择指派的用户");
        }
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(orderIds);
        for (Object o : jsonArray) {
            InspectionOrder inspectionOrder = dao.findModel(StringConverters.null2Long(o));
            if (null == inspectionOrder) {
                throw new RuntimeException("请选择正确的工单信息");
            }
            inspectionOrder.setReceiveUser(systemUser);
            inspectionOrder.setAssign(true);
            inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.WAIT_PRESENCE);
            dao.update(inspectionOrder);
            /*******添加工单日志********/
            inspectionOrderLogBiz.saveInspectionOrderLog(inspectionOrder, InsOrderOperationEnum.TRANSFER, request);


            //工时管理
            InspectionWorkingHours inspectionWorkingHours;
            QueryParam queryParam2 = new QueryParam();
            queryParam2.getSqlMap().put("partnerId", StringConverters.null2String(systemUser.getId()));
            queryParam2.getSqlMap().put("inspectionOrderId", StringConverters.null2String(inspectionOrder.getId()));
            List<InspectionWorkingHours> workingHoursList = inspectionWorkingHoursBiz.findList(queryParam2);
            if (CollectionUtil.isNotEmpty(workingHoursList)) {
                inspectionWorkingHours = workingHoursList.get(0);
            } else {
                inspectionWorkingHours = new InspectionWorkingHours();
                inspectionWorkingHours.setActualWorkingHours(0);
            }
            inspectionWorkingHours.setInspectionOrder(inspectionOrder);
            inspectionWorkingHours.setWorkingHoursStatusEnum(InsWorkingHoursStatusEnum.STOP);
            inspectionWorkingHours.setPartner(systemUser);
            inspectionWorkingHours.setCharge(true);
            inspectionWorkingHours.setEnterprise(sessionEnterprise);
            inspectionWorkingHoursBiz.addOrUpdate(inspectionWorkingHours);

            //消息推送
            String content = "巡检单:" + inspectionOrder.getOrderCode() + "被转单,请接单!";
            List<Long> ids = new ArrayList<>();
            ids.add(StringConverters.null2Long(userId));
            planMessageSendBiz.senMsg(inspectionOrder.getId(), "inspection", inspectionOrder.getEnterprise(), ids, content);
        }
        return ResultUtil.success();
    }

    public ResultDto partnerList(String id) {
        JSONObject result = new JSONObject();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        InspectionOrder inspectionOrder = dao.findModel(StringConverters.null2Long(id));
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("inspectionOrderId", id);
        List<InspectionPartner> inspectionPartners = inspectionPartnerBiz.findList(queryParam);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        if (inspectionOrder.getReceiveUser() != null) {
            jsonObject.put("reason", "");
            jsonObject.put("name", StringConverters.null2String(inspectionOrder.getReceiveUser().getUserName()));
            jsonObject.put("phone", StringConverters.null2String(inspectionOrder.getReceiveUser().getMobile()));
            jsonObject.put("userId", StringConverters.null2String(inspectionOrder.getReceiveUser().getId()));
            jsonObject.put("tag", "main");
            jsonArray.add(jsonObject);
        }

        for (InspectionPartner inspectionPartner : inspectionPartners) {
            jsonObject = new JSONObject();
            jsonObject.put("reason", StringConverters.null2String(inspectionPartner.getReason()));
            jsonObject.put("userId", StringConverters.null2String(inspectionPartner.getPartner().getId()));
            jsonObject.put("name", StringConverters.null2String(inspectionPartner.getPartner().getUserName()));
            jsonObject.put("phone", StringConverters.null2String(inspectionPartner.getPartner().getMobile()));
            jsonObject.put("tag", "partner");
            jsonArray.add(jsonObject);
        }

        result.put("list", jsonArray);
        return ResultUtil.success(result);
    }

    public ResultDto addPartner(String id, String partnerArray) {
        JSONObject result = new JSONObject();
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

        if (StringUtils.isNotBlank(partnerArray)) {
            JSONArray array = JSONArray.parseArray(partnerArray);
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < array.size(); i++) {

                JSONObject j = array.getJSONObject(i);

                String userId = AliJsonObjectCover.ObjectString(j, "userId");

                QueryParam queryParam = new QueryParam();
                queryParam.getSqlMap().put("partnerId", userId);
                queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
                queryParam.getSqlMap().put("inspectionOrderId", id);
                List<InspectionPartner> list = inspectionPartnerBiz.findList(queryParam);
                InspectionPartner inspectionPartner;
                if (CollectionUtils.isNotEmpty(list)) {
                    inspectionPartner = list.get(0);
                } else {
                    inspectionPartner = new InspectionPartner();
                }

                InspectionOrder inspectionOrder = findModel(StringConverters.null2Long(id));
                inspectionPartner.setInspectionOrder(inspectionOrder);
                inspectionPartner.setEnterprise(sessionEnterprise);
                String reason = AliJsonObjectCover.ObjectString(j, "reason");
                if (StringUtils.isNotBlank(reason)) {
                    inspectionPartner.setReason(reason);
                }

                String teamworkCatId = AliJsonObjectCover.ObjectString(j, "teamworkCatId");
                if (StringUtils.isNotBlank(teamworkCatId)) {
                    DictInfo model = dictInfoBiz.findModel(StringConverters.null2Long(teamworkCatId));
                    inspectionPartner.setTeamworkCat(model);
                }

                if (StringUtils.isNotBlank(userId)) {
                    inspectionPartner.setPartner(systemUserBiz.findModel(StringConverters.null2Long(userId)));
                }
                String content = AliJsonObjectCover.ObjectString(j, "content");
                if (StringUtils.isNotBlank(content)) {
                    inspectionPartner.setContent(content);
                }
                inspectionPartnerBiz.addOrUpdate(inspectionPartner);
                jsonArray.add(inspectionPartner.getId());


                //工时管理
                InspectionWorkingHours inspectionWorkingHours;
                QueryParam queryParam2 = new QueryParam();
                queryParam2.getSqlMap().put("partnerId", StringConverters.null2String(systemUser.getId()));
                queryParam2.getSqlMap().put("inspectionOrderId", StringConverters.null2String(inspectionOrder.getId()));
                List<InspectionWorkingHours> inspectionWorkingHoursList = inspectionWorkingHoursBiz.findList(queryParam2);
                if (CollectionUtil.isNotEmpty(inspectionWorkingHoursList)) {
                    inspectionWorkingHours = inspectionWorkingHoursList.get(0);
                } else {
                    inspectionWorkingHours = new InspectionWorkingHours();
                    inspectionWorkingHours.setActualWorkingHours(0);
                }
                inspectionWorkingHours.setInspectionOrder(inspectionOrder);
                inspectionWorkingHours.setWorkingHoursStatusEnum(InsWorkingHoursStatusEnum.RUN);
                inspectionWorkingHours.setPartner(systemUser);
                inspectionWorkingHours.setCharge(false);
                inspectionWorkingHours.setEnterprise(sessionEnterprise);
                inspectionWorkingHoursBiz.addOrUpdate(inspectionWorkingHours);
            }
            result.put("partnerIds", jsonArray);
        }
        return ResultUtil.success(result);
    }

    public ResultDto removePartner(String id) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        inspectionPartnerBiz.deleteLogic(inspectionPartnerBiz.findModel(StringConverters.null2Long(id)));
        return ResultUtil.success();
    }

    public ResultDto getRemark(String contentId) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        JSONObject jsonObject = new JSONObject();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("contentId", contentId);
        List<InspectionWorkContentRemark> inspectionWorkContentRemarks = inspectionWorkContentRemarkBiz.findList(queryParam);
        if (CollectionUtil.isNotEmpty(inspectionWorkContentRemarks)) {
            InspectionWorkContentRemark inspectionWorkContentRemark = inspectionWorkContentRemarks.get(0);
            jsonObject = inspectionWorkContentRemark.toJSONObject();
        }
        return ResultUtil.success(jsonObject);
    }


    public ResultDto addRemark(String contentId, String question, String measure, String remark,Date createDate) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        InspectionWorkContentRemark inspectionWorkContentRemark;
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("contentId", contentId);
        List<InspectionWorkContentRemark> workContentRemarks = inspectionWorkContentRemarkBiz.findList(queryParam);
        if (CollectionUtil.isNotEmpty(workContentRemarks)) {
            inspectionWorkContentRemark = workContentRemarks.get(0);
        } else {
            inspectionWorkContentRemark = new InspectionWorkContentRemark();
            inspectionWorkContentRemark.setInspectionOrderWorkContent(inspectionOrderWorkContentBiz.findModel(StringConverters.null2Long(contentId)));
        }
        if(createDate!=null){
            inspectionWorkContentRemark.setCreateDate(createDate);
        }
        inspectionWorkContentRemark.setQuestion(StringConverters.null2String(question));
        inspectionWorkContentRemark.setMeasure(StringConverters.null2String(measure));
        inspectionWorkContentRemark.setRemark(StringConverters.null2String(remark));
        inspectionWorkContentRemark.setEnterprise(sessionEnterprise);
        inspectionWorkContentRemarkBiz.addOrUpdate(inspectionWorkContentRemark);
        return ResultUtil.success();
    }

    public ResultDto partnerAddMore(String contentArray, String inspectionOrderId) {
        JSONObject result = new JSONObject();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("inspectionOrderId", inspectionOrderId);
        JSONArray jsonArray = new JSONArray();
        List<FacilityInspectionSnap> list = facilityInspectionSnapBiz.findList(queryParam);

        List<String> hadList = new ArrayList<>();
        if (StringUtils.isNotBlank(contentArray)) {
            JSONArray array = JSONArray.parseArray(contentArray);
            for (int i = 0; i < array.size(); i++) {
                JSONObject j = array.getJSONObject(i);
                hadList.add(j.toString());
            }
        }

        for (FacilityInspectionSnap facilityInspectionSnap : list) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("facilityName", StringConverters.null2String(facilityInspectionSnap.getFacilityName()));
            jsonObject.put("facilityId", StringConverters.null2String(facilityInspectionSnap.getFacilityId()));
            jsonObject.put("snapId", StringConverters.null2String(facilityInspectionSnap.getId()));
            Set<InspectionOrderWorkContent> inspectionOrderWorkContents = facilityInspectionSnap.getInspectionOrderWorkContents();
            JSONArray inspectionArray = new JSONArray();
            for (InspectionOrderWorkContent inspectionOrderWorkContent : inspectionOrderWorkContents) {
                JSONObject inspectionObject = new JSONObject();
                inspectionObject.put("contentId", StringConverters.null2String(inspectionOrderWorkContent.getId()));
                inspectionObject.put("contentName", StringConverters.null2String(inspectionOrderWorkContent.getName()));
                JSONObject hadObject = new JSONObject();
                hadObject.put("snapId", StringConverters.null2String(facilityInspectionSnap.getId()));
                hadObject.put("contentId", StringConverters.null2String(inspectionOrderWorkContent.getId()));
                if (CollectionUtils.isNotEmpty(hadList) && hadList.contains(hadObject.toString())) {

                } else {
                    inspectionArray.add(inspectionObject);
                }
            }
            jsonObject.put("contentArray", inspectionArray);
            if (inspectionArray.size() > 0) {
                jsonArray.add(jsonObject);
            }
        }
        result.put("rows", jsonArray);
        return ResultUtil.success(result);
    }

    /**
     * 工作流程
     *
     * @param id
     * @return
     */
    public ResultDto workProgress(String id) {
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }

        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
        queryParam.getSqlMap().put("inspectionOrderId", id);
        String progress = "('RECEIVE_ORDER','RRESENT_ORDER','TRANSFER','SUBMIT_ORDER','TEMP_SUBMIT_ORDER','CANCEL_ORDER','DELAY_ORDER')";//工作流程，接单，到场，转单，完成维保，取消申请，延期申请

        queryParam.getSqlMap().put("progress", progress);
        queryParam.setSqlOrder("order by id");
        List<InspectionOrderLog> inspectionOrderLogBizList = inspectionOrderLogBiz.findList(queryParam);
        JSONArray jsonArray = new JSONArray();
        //开始时间
        InspectionOrder inspectionOrder = dao.findModel(StringConverters.null2Long(id));
        //审批记录
        Set<InsAuditOrder> insAuditOrders = inspectionOrder.getInsAuditOrders();
        insAuditOrders.forEach(x -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("operation", x.getPass() ? (NumberUtil.convert(x.getLevel()) + "级审核") : "驳回");
            jsonObject.put("userName", x.getAuditUser().getUserName());
            jsonObject.put("id", x.getId());
            jsonObject.put("createDate", CommonSugar.getTypedDefault(DateTimeUtils.formatDateToStringWithTime(x.getCreateDate()), ""));
            jsonArray.add(jsonObject);
        });
        //其他日志流程
        JSONObject startObject = new JSONObject();
        startObject.put("createDate", DateTimeUtils.formatDateToStringWithTime(inspectionOrder.getStartDateTime()));
        startObject.put("userName", inspectionOrder.getCreateUser().getUserName());
        startObject.put("id", "0");
        startObject.put("operation", "开始");
        jsonArray.add(startObject);
        for (InspectionOrderLog inspectionOrderLog : inspectionOrderLogBizList) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("createDate", CommonSugar.getTypedDefault(DateTimeUtils.formatDateToStringWithTime(inspectionOrderLog.getCreateDate()), ""));
            jsonObject.put("operation", inspectionOrderLog.getOrderOperationEnum().getName());
            jsonObject.put("userName", inspectionOrderLog.getUserName());
            jsonObject.put("id", inspectionOrderLog.getId());
            jsonArray.add(jsonObject);
        }
        //对jsonArray进行排序
        jsonArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getDate("createDate")));
        JSONObject result = new JSONObject();
        result.put("rows", jsonArray);
        return ResultUtil.success(result);
    }

    /**
     * 查询列表接口
     *
     * @param status 状态 0 待接单，1进行中 2 审核中 3 完成 4批量审核 5批量转单
     * @return
     */
    public ResultDto list(String status, String pageIndex, String pageSize, SystemUser systemUser, Enterprise enterprise, String searchData, String date) {

        /**
         * 工单的批量审核权限
         */
        String auditAuthorityName = "ROLE_INSPECTION_ORDER_BATCH_AUDIT";
        if (StringConverters.null2String(status).equals("4") && !systemAuthorityBiz.hasAuthAuthority(auditAuthorityName, systemUser.getId(), enterprise.getId())) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("records", 0);
            jsonObject.put("rows", new JSONArray());
            return ResultUtil.success(jsonObject);
        }

        /**
         * 判断当前用户是否是部门主管
         */
        boolean isLeader = false;
        String suoHql = "select obj from SystemUserOrganization obj where obj.systemUser.id=" + systemUser.getId() + " and obj.organization.enterprise.id = " + enterprise.getId();
        List<SystemUserOrganization> systemUserOrganizationList = systemUserOrganizationBiz.hqlExcute(suoHql);
        Organization organization = null;
        if (CollectionUtils.isNotEmpty(systemUserOrganizationList) && systemUserOrganizationList.get(0).isLeader()) {
            organization = systemUserOrganizationList.get(0).getOrganization();
            isLeader = true;
        }
//        return dao.list(status, pageIndex, pageSize, systemUser, enterprise, searchData, date, isLeader, organization);
        ResultDto resultDto = new ResultDto();
        try {
            resultDto = dao.list(status, pageIndex, pageSize, systemUser, enterprise, searchData, date, isLeader, organization);
        } catch (Exception ex) {
            logger.error("获取巡检列表失败", ex.getMessage(),ex);
        }
        return resultDto;
    }

    /**
     * 接单方法
     *
     * @param id 工单关键字ID
     * @return
     */
    public ResultDto receive(String id) {
        InspectionOrder inspectionOrder = dao.findModel(StringConverters.null2Long(id));
        if (null == inspectionOrder) {
            return ResultUtil.error("该工单不存在");
        }
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (null == systemUser) {
            return ResultUtil.error("用户未登录");
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == enterprise) {
            return ResultUtil.error("企业信息有误");
        }

        if (!inspectionOrder.getOrderStatusEnum().getCode().equals("WAIT_TAKING")) {
            return ResultUtil.error("该工单已不在待接单列表中，请刷新查看");
        }

        inspectionOrder.setReceiveUser(systemUser);
        inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.WAIT_PRESENCE);
        inspectionOrder.setReceiveDate(new Date());
        inspectionOrder.setReceive(true);
        dao.update(inspectionOrder);
        //操作日志
        inspectionOrderLogBiz.saveInspectionOrderLog(inspectionOrder, InsOrderOperationEnum.RECEIVE_ORDER, request);

        //工时管理
        InspectionWorkingHours inspectionWorkingHours;
        QueryParam queryParam2 = new QueryParam();
        queryParam2.getSqlMap().put("partnerId", StringConverters.null2String(systemUser.getId()));
        queryParam2.getSqlMap().put("inspectionOrderId", StringConverters.null2String(inspectionOrder.getId()));
        List<InspectionWorkingHours> inspectionWorkingHoursList = inspectionWorkingHoursBiz.findList(queryParam2);
        if (CollectionUtil.isNotEmpty(inspectionWorkingHoursList)) {
            inspectionWorkingHours = inspectionWorkingHoursList.get(0);
        } else {
            inspectionWorkingHours = new InspectionWorkingHours();
            inspectionWorkingHours.setActualWorkingHours(0);
        }
        inspectionWorkingHours.setInspectionOrder(inspectionOrder);
        inspectionWorkingHours.setWorkingHoursStatusEnum(InsWorkingHoursStatusEnum.RUN);
        inspectionWorkingHours.setPartner(systemUser);
        inspectionWorkingHours.setCharge(true);
        inspectionWorkingHours.setEnterprise(enterprise);
        inspectionWorkingHoursBiz.addOrUpdate(inspectionWorkingHours);

        //消息推送 TODO
        String content = "巡检单:" + inspectionOrder.getOrderCode() + "已被:" + systemUser.getUserName() + "接单!";
        List<Long> ids = new ArrayList<>();
        ids.add(systemUser.getId());
        planMessageSendBiz.senMsg(inspectionOrder.getId(), "inspection", inspectionOrder.getEnterprise(), ids, content);

        return ResultUtil.success();
    }

    /**
     * 到场方法
     *
     * @param id 工单关键字ID
     * @return
     */
    public ResultDto present(String id, String longitude, String latitude) {
        InspectionOrder inspectionOrder = dao.findModel(StringConverters.null2Long(id));
        if (null == inspectionOrder) {
            return ResultUtil.error("该工单不存在");
        }
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        if (null == systemUser) {
            return ResultUtil.error("用户未登录");
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == enterprise) {
            return ResultUtil.error("企业信息有误");
        }
        inspectionOrder.setPresenceUser(systemUser);
        inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.UNFINISHED);
        inspectionOrder.setPresenceTime(new Date());
        inspectionOrder.setPresence(true);
        inspectionOrder.setLongitude(StringConverters.null2BigDecimal(longitude));
        inspectionOrder.setLatitude(StringConverters.null2BigDecimal(latitude));
        inspectionOrder.setMark(false);
        dao.update(inspectionOrder);
        //操作日志
        inspectionOrderLogBiz.saveInspectionOrderLog(inspectionOrder, InsOrderOperationEnum.RRESENT_ORDER, request);
        return ResultUtil.success();
    }

    public ResultDto upload(MultipartFile file, String type) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (file == null || StringUtils.isBlank(type)) {
            return ResultUtil.error("参数错误");
        }
        Resource resource = new Resource();
        String savePath = "";
        if ("img".equals(type)) {
            savePath = FileUtils.fileUpload(file, ConstantKeyFilePath.INSPECTION_IMG_DIR, ConstantKeyFilePath.INSPECTION_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
            resource.setResourceName("巡检工作内容图片");
            resource.setResourceTypeEnum(ResourceTypeEnum.IMG);
        }
        resource.setPath(savePath);
        resource.setEnterprise(sessionEnterprise);
        resource.setCreateDate(new Date());
        resourceBiz.addOrUpdate(resource);
        return ResultUtil.success(resource.toJSONObject());
    }
    public ResultDto uploads(MultipartFile[] file, String type,String moduleType) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (systemUser == null || sessionEnterprise == null) {
            ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (file == null || StringUtils.isBlank(type)) {
            return ResultUtil.error("参数错误");
        }
        JSONArray jsonArray=new JSONArray();
        for(int i=0;i<file.length;i++){
            Resource resource = new Resource();
            String savePath = "";
            if ("img".equals(type)) {
                if(("inspection").equals(moduleType)){
                    savePath = FileUtils.fileUpload(file[i], ConstantKeyFilePath.INSPECTION_IMG_DIR, ConstantKeyFilePath.INSPECTION_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
                    resource.setResourceName("巡检图片");
                }else{
                    savePath = FileUtils.fileUpload(file[i], ConstantKeyFilePath.REPAIR_IMG_DIR, ConstantKeyFilePath.REPAIR_IMG_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
                    resource.setResourceName("巡检异常报修");
                }
                resource.setResourceTypeEnum(ResourceTypeEnum.IMG);

                }else if ("mp3".equals(type)) {
                    savePath = FileUtils.fileUpload(file[i], ConstantKeyFilePath.REPAIR_MP3_DIR, ConstantKeyFilePath.REPAIR_MP3_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
                    resource.setResourceName("设备报修录音");
                    resource.setResourceTypeEnum(ResourceTypeEnum.MP3);
            }
            if(StringUtils.isEmpty(savePath)) {
                return ResultUtil.error();
            }
            resource.setPath(savePath);
            resource.setEnterprise(sessionEnterprise);
            resource.setCreateDate(new Date());
            resourceBiz.addOrUpdate(resource);
            jsonArray.add(resource.getId());
        }
        return ResultUtil.success(jsonArray);
    }

    /**
     * 工单终极审核  打分和评价接口
     *
     * @param orderId
     * @param score
     * @param remark 最终评分
     * @return
     */
    public ResultDto finalAudit(String orderId, String score, String remark) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        InspectionOrder inspectionOrder = dao.findModel(StringConverters.null2Long(orderId));
        if (null != inspectionOrder) {
               /* int level = maintainOrder.getLevel();
                maintainOrder.setLevel(0);
                maintainOrder.setAuditing(false);//审核完结  置为初始
                maintainOrder.setPosition(null);
                maintainOrder.setAuditSystemUser(null);
                maintainOrder.setOrganization(null);
                maintainOrder.setAuditLast(false);
                maintainOrder.setAuditFirst(false);*/
            inspectionOrder.setScore(StringConverters.null2Int(score));
            inspectionOrder.setLastRemark(remark);
            if(inspectionOrder.getOrderStatusEnum().getCode().equals("IN_AUDITING")){
                inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.COMPLETED);
            }else if(inspectionOrder.getDelay()){
                inspectionOrder.setEndDateTime(inspectionOrder.getDelayTime());
            }
            /*        maintainOrder.setOrderStatusEnum(OrderStatusEnum.COMPLETED);*/
            dao.update(inspectionOrder);
            /*       *//*****添加审核日志*****//*
                auditOrderBiz.saveOrUpdate(maintainOrder, systemUser, true, remark, AuditTypeEnum.COMPLETE, level);
                //操作日志
                maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.AUDIT, request);*/
        }
        return ResultUtil.success();
    }

    public ResultDto addRepair(String inspectionCode, String repairCode, String contentId, boolean inspectionOrder) {
        InspectionToRepair inspectionToRepair;
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("contentId", contentId);
        queryParam.getSqlMap().put("inspectionCode", inspectionCode);
        queryParam.getSqlMap().put("repairCode", repairCode);
        List<InspectionToRepair> list = inspectionToRepairBiz.findList(queryParam);
        if (CollectionUtil.isNotEmpty(list)) {
            inspectionToRepair = list.get(0);
        } else {
            inspectionToRepair = new InspectionToRepair();
        }
        inspectionToRepair.setInspectionCode(inspectionCode);
        inspectionToRepair.setRepairCode(repairCode);
        inspectionToRepair.setInspectionOrder(inspectionOrder);
        inspectionToRepair.setContentId(StringConverters.null2Long(contentId));
        inspectionToRepairBiz.addOrUpdate(inspectionToRepair);
        return ResultUtil.success();
    }

    public ResultDto relateRepairOrder(String inspectionCode) {
        JSONObject result = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("inspectionCode", inspectionCode);
        List<InspectionToRepair> list = inspectionToRepairBiz.findList(queryParam);
        for (InspectionToRepair inspectionToRepair : list) {
            jsonArray.add(inspectionToRepair.getRepairCode());
        }
        result.put("rows", jsonArray);
        return ResultUtil.success(result);
    }


    public JSONArray getHoursChartsData(String startDateTime, String endDateTime, String organizationId,String enterpriseId) {
        JSONArray result = new JSONArray();

        List<Object> hoursChartsData = dao.getHoursChartsData(startDateTime, endDateTime, organizationId,enterpriseId);
        for (Object data : hoursChartsData) {
            result.add(StringConverters.null2Int(data));
        }
        return result;
    }

    /**
     * 自定义hql查询接口
     *
     * @param hql
     * @param queryParam
     * @return
     */
    public List<InspectionOrder> hqlExcute(String hql, QueryParam queryParam) {
        return dao.hqlExcute(hql, queryParam);
    }

    /**
     * 查看工作内容（设备和工艺）接口
     *
     * @param facilityId
     * @param inspectionTechnologyId
     * @return
     */
    public ResultDto getFacilityAndTechnology(String facilityId, String inspectionTechnologyId) {
        Facility facility = facilityBiz.findModel(StringConverters.ToLong(facilityId));
        InspectionTechnology inspectionTechnology = inspectionTechnologyBiz.findModel(StringConverters.ToLong(inspectionTechnologyId));
        JSONObject result = new JSONObject();
        JSONObject data = new JSONObject();
        if (facility == null && inspectionTechnology == null) {
            return ResultUtil.error("数据异常！");
        }
        JSONObject facilityJson = new JSONObject();
        if (facility != null) {
            facilityJson = facility.toDetailJSONObject();
            //设备专业名称
            facilityJson.put("rootCatName", "");
            if (facility.getFacilityCat() != null) {
                FacilityCat rootCat = facilityCatBiz.findRootCat(facility.getFacilityCat().getId());
                facilityJson.put("rootCatName", StringConverters.null2String(rootCat.getCatName()));
            }
        }
        JSONObject inspectionTechnologyJson = new JSONObject();
        if (inspectionTechnology != null) {
            inspectionTechnologyJson = inspectionTechnology.toJSONObject();
            JSONArray inspectionDataArray = new JSONArray();
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("inspectionTechnologyId", inspectionTechnologyId);
            List<InspectionData> inspectionDataList = inspectionDataBiz.findList(queryParam);
            if (CollectionUtils.isNotEmpty(inspectionDataList)) {
                for (InspectionData inspectionData : inspectionDataList) {
                    JSONObject inspectionDataJson = inspectionData.toJSONObject3();
                    inspectionDataArray.add(inspectionDataJson);
                }
            }
            inspectionTechnologyJson.put("inspectionData", inspectionDataArray);
        }
        data.put("facility", facilityJson);
        data.put("inspectionTechnology", inspectionTechnologyJson);
        result.put("data", data);
        return ResultUtil.success(result);
    }


    /**
     * 计算预计工时
     */
    public long updateExpectWorkingHours(String inspectionOrderId) {
        if (StringUtils.isBlank(inspectionOrderId)) {
            return 0;
        }
        //更新预计工时
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("inspectionOrderId", inspectionOrderId);
        List<FacilityInspectionSnap> facilityInspectionSnapList = facilityInspectionSnapBiz.findList(queryParam);
        long expectWorkingHours = 0L;
        if (CollectionUtils.isNotEmpty(facilityInspectionSnapList)) {
            for (FacilityInspectionSnap facilityInspectionSnap : facilityInspectionSnapList) {
                if (facilityInspectionSnap != null) {
                    InspectionTechnology inspectionTechnology = inspectionTechnologyBiz.findModel(facilityInspectionSnap.getInspectionId());
                    if (inspectionTechnology != null && StringUtils.isNotBlank(inspectionTechnology.getEstimateTime())) {
                        long estimateTime = 0;
                        try {
                            estimateTime = Long.valueOf(inspectionTechnology.getEstimateTime());
                        } catch (Exception e) {
                            logger.info("转long失败");
                        }
                        expectWorkingHours += estimateTime;
                    }
                }
            }
        }
        return expectWorkingHours;
    }

    public JSONObject countScore(String enterpriseId, String systemUserId) {
        JSONObject result = new JSONObject();
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("systemUserId", systemUserId);
        List<Long> ids = new ArrayList<>();
        String idArray = com.useeinfo.framework.sugar.func.lang.StringUtils.strip(ids.toString(), "[]");
        List<Enterprise> enterprises = enterpriseBiz.findList(queryParam);
        for (Enterprise enterprise : enterprises) {
            ids.add(enterprise.getId());
        }
        List<String> list = new ArrayList<>();
        list.add("4");
        list.add("5");
        int score_0 = StringConverters.null2Int(dao.countScore("0", ids).get(0));
        int score_1 = StringConverters.null2Int(dao.countScore("1", ids).get(0));
        int score_2 = StringConverters.null2Int(dao.countScore("2", ids).get(0));
        int score_3 = StringConverters.null2Int(dao.countScore("3", ids).get(0));
        int score_4 = StringConverters.null2Int(dao.countScore("4", ids).get(0));
        int score_5 = StringConverters.null2Int(dao.countScore("5", ids).get(0));
        int totalScore = StringConverters.null2Int(dao.countScore("", ids).get(0));
        int score_achieve = StringConverters.null2Int(dao.countScore(StringUtils.strip(list.toString(), "[]"), ids).get(0));
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("num", score_5);
        jsonObject.put("name", "A");
        jsonObject.put("percent", DataHandleUtil.division(score_5, totalScore));
        jsonArray.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", score_4);
        jsonObject.put("name", "B");
        jsonObject.put("percent", DataHandleUtil.division(score_4, totalScore));
        jsonArray.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", score_3);
        jsonObject.put("name", "C");
        jsonObject.put("percent", DataHandleUtil.division(score_3, totalScore));
        jsonArray.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", score_2);
        jsonObject.put("name", "D");
        jsonObject.put("percent", DataHandleUtil.division(score_2, totalScore));
        jsonArray.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", score_1);
        jsonObject.put("name", "E");
        jsonObject.put("percent", DataHandleUtil.division(score_1, totalScore));
        jsonArray.add(jsonObject);
        jsonObject = new JSONObject();
        jsonObject.put("num", score_0);
        jsonObject.put("name", "F");
        jsonObject.put("percent", DataHandleUtil.division(score_0, totalScore));
        jsonArray.add(jsonObject);
        result.put("scores", jsonArray);
        result.put("totalNum", totalScore);
        result.put("achieve", DataHandleUtil.division(score_achieve, totalScore));
        return result;
    }


    /**
     * 参与人详情
     *
     * @param id
     * @param userId
     * @param tag
     * @return
     */
    public ResultDto partnerDetail(String id, String userId, String tag) {
        JSONObject jsonObject = new JSONObject();
        SystemUser systemUser = systemUserBiz.findModel(StringConverters.null2Long(userId));
        jsonObject.put("name", systemUser.getUserName());
        jsonObject.put("phone", systemUser.getMobile());
        InspectionOrder inspectionOrder = dao.findModel(StringConverters.null2Long(id));
        JSONArray contentArray = new JSONArray();
        if ("partner".equals(tag)) {
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(inspectionOrder.getEnterprise().getId()));
            queryParam.getSqlMap().put("inspectionOrderId", id);
            queryParam.getSqlMap().put("partnerId", userId);
            List<InspectionPartner> inspectionPartnerList = inspectionPartnerBiz.findList(queryParam);
            if (CollectionUtils.isNotEmpty(inspectionPartnerList) && inspectionPartnerList.size() == 1) {
                InspectionPartner inspectionPartner = inspectionPartnerList.get(0);
                jsonObject.put("reason", inspectionPartner.getReason());
                jsonObject.put("teamworkCat", inspectionPartner.getTeamworkCat() == null ? "" : inspectionPartner.getTeamworkCat().getPropertyName());
                Set<String> snapSet = new HashSet<>();
                JSONArray jsonArray = JSONArray.parseArray(inspectionPartner.getContent());
                for (int i = 0; i < jsonArray.size(); i++) {
                    snapSet.add(jsonArray.getJSONObject(i).getString("snap"));
                }
                snapSet.forEach(x -> {
                    JSONObject contentObject = new JSONObject();
                    contentObject.put("facilityName", facilityInspectionSnapBiz.findModel(StringConverters.null2Long(x)).getFacilityName());
                    JSONArray contentDetail = new JSONArray();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        if (x.equals(jsonArray.getJSONObject(i).getString("snap"))) {
                            contentDetail.add(inspectionOrderWorkContentBiz.findModel(StringConverters.null2Long(jsonArray.getJSONObject(i).get("content"))).getName());
                        }
                    }
                    contentObject.put("contentDetail", contentDetail);
                    contentArray.add(contentObject);
                });
            }
        } /*else if ("main".equals(tag)) {
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("maintainOrderId", id);
            List<FacilityMaintainSnap> facilityMaintainSnaps = facilityMaintainSnapBiz.findList(queryParam);
            facilityMaintainSnaps.forEach(x -> {
                JSONObject contentObject = new JSONObject();
                contentObject.put("facilityName", x.getFacilityName());
                QueryParam contentParam = new QueryParam();
                contentParam.getSqlMap().put("distribute", "true");
                contentParam.getSqlMap().put("facilityMaintainSnapId", x.getId() + "");
                List<MaintainOrderWorkContent> maintainOrderWorkContents = maintainOrderWorkContentBiz.findList(queryParam);
                JSONArray contentDetail = new JSONArray();
                maintainOrderWorkContents.forEach(y -> {
                    contentDetail.add(y.getName());
                });
                contentObject.put("contentDetail", contentDetail);
                contentArray.add(contentObject);
            });
        }*/
        jsonObject.put("row", contentArray);
        return ResultUtil.success(jsonObject);
    }

    /**
     * 正在维修中的设备
     *
     * @return
     */
    public JSONArray inspectionFacilityCount(String enterpriseIds) {
        JSONArray rows = new JSONArray();
        if (StringUtils.isBlank(enterpriseIds)) {
            return rows;
        }
        List<Object[]> objects = dao.inspectionFacilityCount(enterpriseIds);
        for (Object obj : objects) {
            Long facilityId = Long.parseLong(obj.toString());
            if (facilityId > 0) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("facilityId", facilityId + "");
                rows.add(jsonObject);
            }
        }
        return rows;
    }

    public JSONArray getTags(InspectionOrder inspectionOrder, SystemUser systemUser, String status) {
        return dao.getTags(inspectionOrder, systemUser, status);
    }


    /**
     * dashboard-获取分区响应时间-巡检
     */
    public JSONArray getInspectionOrderResponseTime(Map<String, Object> dataMap) {
        JSONArray jsonArray = new JSONArray();
        List objects = dao.getInspectionOrderResponseTime(dataMap);
        if (CollectionUtils.isNotEmpty(objects)) {
            try {
                for (Object object : objects) {
                    net.sf.json.JSONArray j = net.sf.json.JSONArray.fromObject(object);
                    jsonArray.add( AnalysisObjectList.getJsonString(j, 2));
                }
            } catch (Exception e) {
                logger.info("数据异常");
            }
        }
        return jsonArray;
    }

    //指定人员信息
    public ResultDto getUser(String pageIndex,String pageSize,Enterprise enterprise,String userName,String userIds){

        QueryParam queryParam = new QueryParam(pageIndex, pageSize);
        String userHql = "select obj from SystemUser obj where obj.deleteStatus is false and obj.operationRole='common' and " +
                "exists( select er from obj.enterpriseSet er" +
                " where er.id=" + enterprise.getId() + ")";
        if (!StringConverters.null2String(userName).equals("")) {
            userHql += " and obj.userName like '%" + userName + "%'";
        }

        if (!StringConverters.null2String(userIds).equals("")) {
            String ids = "";
            for (Object object : JSONArray.parseArray(userIds)) {
                if (ids.equals("")) {
                    ids = StringConverters.null2String(object);
                } else {
                    ids += "," + StringConverters.null2String(object);
                }
            }
            if (!StringConverters.null2String(ids).equals("")) {
                userHql += "  and obj.id not in(" + StringConverters.null2String(ids) + ")";
            }

        }
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject;
        for (SystemUser systemUser : systemUserBiz.hqlExcute(userHql, queryParam)) {
            jsonArray.add(systemUser.toJSONObject());
        }
        return ResultUtil.success(jsonArray);
    }

    //指定岗位信息
    public ResultDto getPosition(String pageIndex,String pageSize,Enterprise enterprise,String positionIds){

        QueryParam queryParam = new QueryParam(pageIndex,pageSize);
        String posHql = "select obj from Position obj where obj.deleteStatus is false and obj.enterprise.id="+enterprise.getId();
        if (!StringConverters.null2String(positionIds).equals("")) {
            String ids = "";
            for (Object object : JSONArray.parseArray(positionIds)) {
                if (ids.equals("")) {
                    ids = StringConverters.null2String(object);
                } else {
                    ids += "," + StringConverters.null2String(object);
                }
            }
            if (!StringConverters.null2String(ids).equals("")) {
                posHql += "  and obj.id not in(" + StringConverters.null2String(ids) + ")";
            }

        }
        JSONArray jsonArray = new JSONArray();
        for(Position position:positionBiz.hqlExcute(posHql,queryParam)){
            jsonArray.add(position.toJSONObject());
        }
        //String authorityName = Configuration.getConfigurationByName("inspectionAuthorityName");
        return ResultUtil.success(jsonArray);
    }


    //缓存内容
    public ResultDto cacheOrderInfo(String id,boolean type) {
        SystemUser sessionUser = SessionKeyUtils.getSessionUser(httpServletRequest);
        Enterprise sessionEnterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (sessionUser == null || sessionEnterprise == null) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        InspectionOrder inspectionOrder = dao.findModel(StringConverters.null2Long(id));
        if (null == inspectionOrder) {
            return ResultUtil.error("该工单不存在");
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);
        if (null == enterprise) {
            return ResultUtil.error("企业信息有误");
        }
        if (!inspectionOrder.getOrderStatusEnum().getCode().equals("WAIT_PRESENCE") && !inspectionOrder.getOrderStatusEnum().getCode().equals("UNFINISHED")) {
            return ResultUtil.error("该状态下不能缓存");
        }
        if(!type){ //取消缓存功能
            inspectionOrder.setCache(false);
//            inspectionOrder.setAbnormal(true);
            this.addOrUpdate(inspectionOrder);
            return ResultUtil.success();
        }
        //1 基础数据
        JSONObject jsonObject = inspectionOrder.toJSONObject();//基础信息



        //2工作流程
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONObject.fromObject(this.workProgress(id).getData().toString()).getJSONArray("rows");
        jsonObject.put("workProgress", jsonArray);
        //3工作日志,日志类型，重要程度
        jsonObject.put("workLogType",dictInfoBiz.getDictSelect(enterprise,"INSPECTION_WORK_LOG_CAT"));
        jsonObject.put("workLogLevel",dictInfoBiz.getDictSelect(enterprise,"INSPECTION_WORK_LOG_LEVEL"));
        //人员信息，岗位信息，用于巡检报修的指定人员和岗位
        jsonObject.put("assignUser",getUser("-1","-1",enterprise,null,"[]"));
        jsonObject.put("assignPosition",getPosition("-1","-1",enterprise,"[]"));

        //报修 紧急程度,需要判断是否与这个模块，有才能报修，没有则不能报修
        //获取该企业下配置的应用模块
        enterprise = enterpriseBiz.findModel(StringConverters.null2Long(SessionKeyUtils.getSessionEnterprise(request).getId()));
        QueryParam queryParamType = new QueryParam();
        queryParamType.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        queryParamType.getSqlMap().put("remark", "REPAIR");
        List<ApplicationModule> applicationModules=applicationModuleBiz.findList(queryParamType);
        if(CollectionUtils.isEmpty(applicationModules)){
           jsonObject.put("isRepair",false);
        }else{
            jsonObject.put("isRepair",true);
            QueryParam queryParam = new QueryParam(-1, -1);
            queryParam.setSqlOrder("order by id");
            queryParam.getSqlMap().put("enterpriseId", StringConverters.null2String(sessionEnterprise.getId()));
            jsonObject.put("repairLevel",repairLevelBiz.findJSONList(queryParam));//紧急程度
        }
        //4维保内容，包含设备工艺，pdf,备注
        JSONArray buttons = new JSONArray();
        JSONArray unfinished = new JSONArray();
        JSONArray finished = new JSONArray();
        QueryParam inspectionParam = new QueryParam();
        inspectionParam.getSqlMap().put("inspectionOrderId", StringConverters.null2String(inspectionOrder.getId()));
        List<FacilityInspectionSnap> FacilityInspectionSnaps = facilityInspectionSnapBiz.findList(inspectionParam);
        logger.info("缓存接口,FacilityInspectionSnaps {}",StringConverters.null2String(inspectionOrder.getId()));

        //工作日志
        QueryParam logParam = new QueryParam(-1, -1);
        logParam.getSqlMap().put("inspectionOrderId", id);
        jsonObject.put("workLog",inspectionWorkLogBiz.findJSONList(logParam).getJSONArray("list"));
        //异常备注
        JSONArray remarkArray = new JSONArray();
        for (FacilityInspectionSnap facilityInspectionSnap : FacilityInspectionSnaps) {
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("facilityInspectionSnapId", StringConverters.null2String(facilityInspectionSnap.getId()));
            List<InspectionOrderWorkContent> inspectionOrderWorkContents = inspectionOrderWorkContentBiz.findList(queryParam);
            for (InspectionOrderWorkContent inspection : inspectionOrderWorkContents) {
                //异常备注
                QueryParam contentParam = new QueryParam();
                contentParam.getSqlMap().put("contentId", StringConverters.null2String(inspection.getId()));
                //异常备注
                List<InspectionWorkContentRemark> inspectionWorkContentRemarks = inspectionWorkContentRemarkBiz.findList(contentParam);
                if (CollectionUtils.isNotEmpty(inspectionWorkContentRemarks)) {
                    for (InspectionWorkContentRemark remark : inspectionWorkContentRemarks) {
                        remarkArray.add(remark.toJSONObject());
                    }
                }

            }
        }
        jsonObject.put("workRemark",remarkArray);
        //工时计算
        net.sf.json.JSONObject workingTime = net.sf.json.JSONObject.fromObject(nowWorkHours(id).getData());
        if (inspectionOrder.getOrderStatusEnum().getCode().equals("UNFINISHED")) {
            jsonObject.put("totalWorkingHours", workingTime.get("totalHours"));//总工时
            jsonObject.put("workingHours", workingTime.get("receiveHours"));//我的工时
        }
        //工艺设备信息
        for (FacilityInspectionSnap facilityInspectionSnap : FacilityInspectionSnaps) {
            JSONObject inspectionObject = new JSONObject();
            Facility facility=facilityBiz.findModel(facilityInspectionSnap.getFacilityId());
            inspectionObject.put("facilityName", StringConverters.null2String(facilityInspectionSnap.getFacilityName()));
            inspectionObject.put("facilityCode", StringConverters.null2String(facilityInspectionSnap.getFacilityCode()));
            inspectionObject.put("facilityId", facilityInspectionSnap.getFacilityId());
            inspectionObject.put("applicationId", facilityInspectionSnap.getApplicationScenariosId() == null ? "" : facilityInspectionSnap.getApplicationScenariosId());
            inspectionObject.put("inspectionName", StringConverters.null2String(facilityInspectionSnap.getInspectionName()));
            inspectionObject.put("spec", StringConverters.null2String(facilityInspectionSnap.getSpec()));
            inspectionObject.put("QRCode", StringConverters.null2String(facility.getQrCode()));//二维码值
            inspectionObject.put("facilityPosition", facility.getPosition()+ facility.getPrecisePosition()+facility.getDetailPosition());//位置
            inspectionObject.put("areaId", facility.getArea()!=null?facility.getArea().getId():"");//区域id
            inspectionObject.put("areaName", facility.getArea()!=null?facility.getArea().getAreaName():"");//区域名称
            FacilityCat facilityCat=facilityCatBiz.findModel(facility.getRootCatId());
            inspectionObject.put("rootCatId", facilityCat!=null?facilityCat.getId():"");//报修专业id
            inspectionObject.put("rootCatName", facilityCat!=null?facilityCat.getCatName():"");//报修专业名称
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("facilityInspectionSnapId", StringConverters.null2String(facilityInspectionSnap.getId()));
            List<InspectionOrderWorkContent> inspectionOrderWorkContents = inspectionOrderWorkContentBiz.findList(queryParam);
            JSONArray contentArray = new JSONArray();
            JSONArray applicationArray = new JSONArray();
            for (InspectionOrderWorkContent inspection : inspectionOrderWorkContents) {
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("applicationName", inspection.getApplication_scenarios_name());
                jsonObject1.put("applicationId", inspection.getApplication_scenarios_id());
                if (!applicationArray.contains(jsonObject1)) {
                    applicationArray.add(jsonObject1);
                }
            }
            inspectionObject.put("snapId", facilityInspectionSnap.getId());
            inspectionObject.put("applicationArray", applicationArray);
            //设备详情信息
            for (InspectionOrderWorkContent inspection : inspectionOrderWorkContents) {
                JSONObject contentObject = new JSONObject();
                contentObject.put("inputTypeEnum", StringConverters.null2String(inspection.getInputTypeEnum().getCode()));
                if ("COMPLETE_TYPE".equals(inspection.getInputTypeEnum().getCode()) || "STATUS_TYPE".equals(inspection.getInputTypeEnum().getCode())) {
                    String[] names = inspection.getInputTypeEnum().getName().split("、");
                    JSONArray nameArray = new JSONArray();
                    JSONObject nameS = new JSONObject();
                    nameS.put("content", "尚未选择");
                    nameS.put("isNormal", false);
                    nameArray.add(nameS);
                    for (String o : names) {
                        JSONObject nameStatus = new JSONObject();
                        if ("异常".equals(o) || "无此项目".equals(o) || "需处理（不能运转）".equals(o)) {
                            nameStatus.put("isNormal", false);
                        } else {
                            nameStatus.put("isNormal", true);
                        }
                        nameStatus.put("content", o);
                        nameArray.add(nameStatus);
                    }
//                    nameArray.addAll(Arrays.asList(names));
                    contentObject.put("inputType", nameArray);
                } else {
                    contentObject.put("inputType", StringConverters.null2String(inspection.getInputTypeEnum().getName()));
                }
                contentObject.put("contentId", StringConverters.null2Long(inspection.getId()));
                contentObject.put("unit", StringConverters.null2String(inspection.getUnit()));
                contentObject.put("applicationId", StringConverters.null2Long(inspection.getApplication_scenarios_id()));
                contentObject.put("applicationName", StringConverters.null2String(inspection.getApplication_scenarios_name()));
                contentObject.put("photo", StringConverters.null2Boolean(inspection.getPhoto()));
                contentObject.put("maxNumber", StringConverters.null2Double(inspection.getMaxNumber()));
                contentObject.put("minNumber", StringConverters.null2Double(inspection.getMinNumber()));
                contentObject.put("abnormal", StringConverters.null2Boolean(inspection.getAbnormal()));
                contentObject.put("name", StringConverters.null2String(inspection.getName()));
                contentObject.put("content", StringConverters.null2String(inspection.getContent()));
                JSONArray array = new JSONArray();
                if (StringUtils.isNotBlank(inspection.getContent())) {
                    array = JSONArray.parseArray(inspection.getContent());
                }
                contentObject.put("contentArray", array);
                contentObject.put("category", StringConverters.null2String(inspection.getCategory()));
                contentObject.put("result", StringConverters.null2String(inspection.getResult()));
                JSONArray photoArray = new JSONArray();
                if (inspection.getContentPhoto() != null) {
                    List<Resource> contentPhotos = new ArrayList<>(inspection.getContentPhoto());
                    contentPhotos.sort((o1, o2) -> o1.getId() < o2.getId() ? -1 : 1);
                    if (CollectionUtils.isNotEmpty(contentPhotos)) {
                        for (Resource resource : contentPhotos) {
                            photoArray.add(resource.getPath());
                        }
                    }
                }
                contentObject.put("photos", photoArray);
                String path = "";
                if (StringUtils.isNotBlank(inspection.getResourceIds())) {
                    Resource model = resourceBiz.findModel(StringConverters.null2Long(inspection.getResourceIds()));
                    if (model != null) {
                        path = model.getPath();
                    }
                }
                contentObject.put("resources", path);
                contentArray.add(contentObject);
            }
            inspectionObject.put("contents", contentArray);
            if (facilityInspectionSnap.isCompleted()) {
                finished.add(inspectionObject);
            } else {
                unfinished.add(inspectionObject);
            }
        }
        //未完成设备，已完成设备
        jsonObject.put("finished", finished);
        jsonObject.put("unfinished", unfinished);

        // 巡检接单权限
        String takingAuthorityName = "ROLE_ENTERPRISE_INSPECTION_ORDER_TAKING";

        //按钮，临时保存，提交，到场
        if ("WAIT_PRESENCE".equals(inspectionOrder.getOrderStatusEnum().getCode())) {
            if (systemAuthorityBiz.hasAuthAuthority(takingAuthorityName, sessionUser.getId(), enterprise.getId())) {
                buttons.add("presenceButton");
            }
        }else if  ("UNFINISHED".equals(inspectionOrder.getOrderStatusEnum().getCode())) {
            buttons.add("saveButton");
            buttons.add("submitButton");
        }

        //参与人信息
        QueryParam partnerParam = new QueryParam();
        partnerParam.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
        partnerParam.getSqlMap().put("inspectionOrderId", StringConverters.null2String(inspectionOrder.getId()));
        List<InspectionPartner> partners = inspectionPartnerBiz.findList(partnerParam);
        JSONArray partnerArray = new JSONArray();
        for (InspectionPartner inspectionPartner : partners) {
            JSONObject partnerObject = new JSONObject();
            partnerObject.put("deleteStatus", inspectionPartner.isDeleteStatus());
            partnerObject.put("partnerId", inspectionPartner.getId());
            partnerObject.put("userId", inspectionPartner.getPartner().getId());
            partnerObject.put("userName", inspectionPartner.getPartner().getUserName());
            partnerObject.put("workingHours", inspectionPartner.getWorkingHours());
            partnerArray.add(partnerObject);
        }
        jsonObject.put("partner", partnerArray);
        jsonObject.put("buttons", buttons);
        jsonObject.put("systemUserId", sessionUser.getId());
        //更改字段
        inspectionOrder.setCache(true);
        this.addOrUpdate(inspectionOrder);
        //小标签
        JSONArray tags = new JSONArray();
        JSONObject tag;
//        if(inspectionOrder.isCache()){
//            tag = new JSONObject();
//            tag.put("name", "已缓存");
//            tag.put("color", "full-orange");
//            tags.add(tag);
//        }


        if (inspectionOrder.isOrderType()) {
            tag = new JSONObject();
            tag.put("name", "一次性");
            tag.put("color", "blue");
            tags.add(tag);
        } else {
            tag = new JSONObject();
            tag.put("name", "周期性");
            tag.put("color", "blue");
            tags.add(tag);
        }
        if (null != inspectionOrder.getOrderAssignTypeEnum()) {
            tag = new JSONObject();
            tag.put("name", "被指派");
            tag.put("color", "blue");
            tags.add(tag);
        }

        if (inspectionOrder.getDelayRealTime() != null && inspectionOrder.getDelayRealTime().before(new Date())) {
            tag = new JSONObject();
            tag.put("name", "逾期");
            tag.put("color", "blue");
            tags.add(tag);
        }
        if (inspectionOrder.isAbnormal()) {
            tag = new JSONObject();
            tag.put("name", "异常");
            tag.put("color", "red");
            tags.add(tag);
        }
        if (inspectionOrder.getDelay()) {
            tag = new JSONObject();
            tag.put("name", "延期");
            tag.put("color", "blue");
            tags.add(tag);
        }
        if (inspectionOrder.getCancel()) {
            tag = new JSONObject();
            tag.put("name", "取消");
            tag.put("color", "blue");
            tags.add(tag);
        }
        jsonObject.put("tags", tags);

        return ResultUtil.success(jsonObject);
    }

    //实时工时
    public ResultDto nowWorkHours(String id) {
        JSONObject jsonObject = new JSONObject();
        long totalHours = 0;
        InspectionOrder inspectionOrder = dao.findModel(StringConverters.null2Long(id));
        if (inspectionOrder == null) {
            jsonObject.put("totalHours", totalHours);
            jsonObject.put("receiveHours", totalHours);
            return ResultUtil.success(jsonObject);
        }
        if (inspectionOrder.getOrderStatusEnum().getCode().equals("UNFINISHED")) {
            totalHours = DateTimeUtils.getDistanceMinutes(inspectionOrder.getPresenceTime(), new Date());
        }
        jsonObject.put("totalHours", inspectionOrder.getTotalWorkingHours()+totalHours);
        jsonObject.put("receiveHours", inspectionOrder.getWorkingHours()+totalHours);
        return ResultUtil.success(jsonObject);
    }


    //保存缓存上传
    public ResultDto saveCacheOrder(String temporaryData, String inspectionOrderId, String presenceDate, String presenceUser, String completeUser, String completeDate, String participantInputs,String workProgress,String workLog,String enterpriseId,String repairOrders,String workRemark) {
        Enterprise enterprise=enterpriseBiz.findModel(StringConverters.null2Long(enterpriseId));
        SystemUser systemUser=systemUserBiz.findModel(StringConverters.null2Long(completeUser));
        if(enterprise==null){
            return ResultUtil.error("session过期，请重新登录");
        }
        logger.info("巡检工单开始执行缓存提交：{}",inspectionOrderId);

        //保存基础数据 到场时间，到场人，完成时间，完成人
        InspectionOrder inspectionOrder = dao.findModel(StringConverters.null2Long(inspectionOrderId));
        if (inspectionOrder.getPresenceTime() == null && StringConverters.ToDateTime(presenceDate) == null) {
            return ResultUtil.error("到场时间不能为空");
        }
        if (systemUserBiz.findModel(StringConverters.null2Long(presenceUser)) == null || systemUserBiz.findModel(StringConverters.null2Long(completeUser)) == null) {
            return ResultUtil.error("到场人和完场人不能为空");
        }
        if (inspectionOrder.getFinishTime() == null && StringConverters.ToDateTime(completeDate) == null) {
            return ResultUtil.error("完成时间不能为空");
        }
        if("COMPLETED".equals(inspectionOrder.getOrderStatusEnum().getCode())||"IN_AUDITING".equals(inspectionOrder.getOrderStatusEnum().getCode())){
            return ResultUtil.success();
        }
        inspectionOrder.setPresence(true);
        inspectionOrder.setPresenceUser(systemUserBiz.findModel(StringConverters.null2Long(presenceUser)));
        inspectionOrder.setPresenceTime(StringConverters.ToDateTime(presenceDate));
        inspectionOrder.setComplete(true);
        inspectionOrder.setCompleteUser(systemUserBiz.findModel(StringConverters.null2Long(completeUser)));
        inspectionOrder.setFinishTime(StringConverters.ToDateTime(completeDate));
        //1保存工时
        //负责人工时计算,工时累加
        long thisHours=DateTimeUtils.newGetDiffMinutesTime(DateTimeUtils.parse("yyyy-MM-dd HH:mm:ss", DateTimeUtils.format(inspectionOrder.getPresenceTime(), "yyyy-MM-dd HH:mm:ss")), StringConverters.ToDateTime(completeDate));
        inspectionOrder.setWorkingHours(inspectionOrder.getWorkingHours()+thisHours);
        //参与人工时计算，工时累加
        long totalWorkingHours=0;
        JSONArray participantInputsArray = JSON.parseArray(participantInputs);
        if (StringUtils.isNotBlank(participantInputs)&&participantInputsArray.size() > 0) {
            for (int i = 0; i < participantInputsArray.size(); i++) {
                JSONObject j = participantInputsArray.getJSONObject(i);
                Long partnerId = AliJsonObjectCover.ObjectLong(j, "userId");
                Long workingHours = AliJsonObjectCover.ObjectLong(j, "workingHours");
                QueryParam q = new QueryParam();
                q.getSqlMap().put("partnerId", partnerId == null ? "-1" : partnerId + "");
                q.getSqlMap().put("inspectionOrderId", inspectionOrder.getId() + "");
                q.getSqlMap().put("enterpriseId", StringConverters.null2String(enterprise.getId()));
                List<InspectionPartner> inspectionPartnerList = inspectionPartnerBiz.findList(q);
                if (CollectionUtils.isEmpty(inspectionPartnerList)) {
                    return ResultUtil.error("参与人不存在！");
                }
                InspectionPartner inspectionPartner = inspectionPartnerList.get(0);
                totalWorkingHours+=workingHours;
                inspectionPartner.setWorkingHours(inspectionPartner.getWorkingHours() + workingHours);
                inspectionPartner.setUpdateDate(StringConverters.ToDateTime(completeDate));
                inspectionPartnerBiz.addOrUpdate(inspectionPartner);
            }
        }
        inspectionOrder.setTotalWorkingHours(thisHours+totalWorkingHours+inspectionOrder.getTotalWorkingHours());
//        inspectionOrder.setAbnormal(true);
        this.addOrUpdate(inspectionOrder);
        //2保存工作流程
        JSONArray workProgressArray = JSON.parseArray(workProgress);
        if(StringUtils.isNotBlank(workProgress)&&workProgressArray.size()>0){
            for (int i = 0; i < workProgressArray.size(); i++) {
                JSONObject jsonObject1=workProgressArray.getJSONObject(i);
                if(!StringUtils.isBlank(jsonObject1.getString("operationCode"))){
                    Date createDate=StringConverters.ToDateTime(jsonObject1.getString("createDate"));//时间取手机本地的时间
                    String id=jsonObject1.getString("id");
                    if(StringUtils.isEmpty(id)){
                        inspectionOrderLogBiz.saveInspectionOrderLogByCache(inspectionOrder,InsOrderOperationEnum.valueOf(jsonObject1.getString("operationCode")),systemUser,enterprise,createDate);
                    }
                }
            }
        }

        //3更新日志
        JSONArray workLogArray = JSON.parseArray(workLog);
        if(StringUtils.isNotBlank(workLog)&&workLogArray.size()>0){
            for (int i = 0; i < workLogArray.size(); i++) {
                JSONObject jsonObject1=workLogArray.getJSONObject(i);
                String typeId=jsonObject1.getString("workLogCatId");
                String levelId=jsonObject1.getString("workLogLevelId");
                String id=jsonObject1.getString("id");

                Date createDate=StringConverters.ToDateTime(jsonObject1.getString("createDate"));

                DictInfo typeInfo=dictInfoBiz.findModel(StringConverters.null2Long(typeId));
                DictInfo levelInfo=dictInfoBiz.findModel(StringConverters.null2Long(levelId));
                if(typeInfo==null){
                    return ResultUtil.error("日志类型不可为空");
                }
                if(levelInfo==null){
                    return ResultUtil.error("重要程度不可为空");
                }
                InspectionWorkLog inspectionWorkLog;
                if(inspectionWorkLogBiz.findModel(StringConverters.null2Long(id))!=null){
                    inspectionWorkLog=inspectionWorkLogBiz.findModel(StringConverters.null2Long(id));
                }else{
                    inspectionWorkLog=new InspectionWorkLog();
                }
                inspectionWorkLog.setEnterprise(enterprise);
                inspectionWorkLog.setLogLevel(levelInfo);
                inspectionWorkLog.setLogCat(typeInfo);
                inspectionWorkLog.setSerial(CommonUtils.getRandomNumber(6));
                inspectionWorkLog.setCode(inspectionWorkLogBiz.getCode(StringConverters.null2String(enterprise.getId())));
                inspectionWorkLog.setSystemUser(systemUser);
                inspectionWorkLog.setContent(jsonObject1.getString("workContent"));
                inspectionWorkLog.setInspectionOrder(inspectionOrder);
                inspectionWorkLog.setCreateDate(createDate);
                Set<Resource> resources=new HashSet<>();
                JSONArray logImgArray=jsonObject1.getJSONArray("photoPaths");
                if(StringUtils.isNotBlank(jsonObject1.getString("photoPaths"))&&logImgArray.size()>0){
                    logImgArray.forEach(x->{
                        Resource resource = resourceBiz.findModel(StringConverters.null2Long(x));
                        resource.setResourceName("工作日志图片");
                        resource.setEnterprise(enterprise);
                        resource.setCreateDate(createDate);
                        resourceBiz.addOrUpdate(resource);
                        resources.add(resource);
                    });
                }
                inspectionWorkLog.setLogPhoto(resources);
                inspectionWorkLogBiz.addOrUpdate(inspectionWorkLog);
            }
        }


        //4保存异常报修工单
        JSONArray repairArray=JSONArray.parseArray(repairOrders);
        if(StringUtils.isNotBlank(repairOrders)&&repairArray.size()>0){
            for(int i=0;i<repairArray.size();i++){
                JSONObject jsonObject=repairArray.getJSONObject(i);
                String assignUser=jsonObject.getString("assignUser");
                String assignPosition=jsonObject.getString("assignPosition");
                String code=jsonObject.getString("code");
                String reportContent=jsonObject.getString("reportContent");
                String reportAddress=jsonObject.getString("reportAddress");
                String reportLevelId=jsonObject.getString("reportLevelId");
                String reportMajorId=jsonObject.getString("reportMajorId");
                Date reportDate=StringConverters.ToDateTime(jsonObject.getString("createDate"));
                String photoPaths=jsonObject.getString("photoPaths");
                String type=jsonObject.getString("type");
                String areaId=jsonObject.getString("areaId");
                String recordingPath=jsonObject.getString("recordingPath");
                String facilityPosition=jsonObject.getString("facilityPosition");
                ResultDto dto=repairOrderBiz.addRepair(assignUser,assignPosition,code,reportContent,reportAddress,reportLevelId,reportMajorId,photoPaths,recordingPath,type,areaId,facilityPosition,systemUser,enterprise,reportDate);
                String reportCode= null;
                if (dto != null) {
                    if (dto.getData() != null) {
                        reportCode = net.sf.json.JSONObject.fromObject(dto.getData()).getString("code");
                    }
                }

                this.addRepair(inspectionOrder.getOrderCode(), reportCode,inspectionOrderId,false);
            }
        }


        //5更新巡检内容  包括工艺信息，照片，异常备注
        JSONArray jsonArray = JSONArray.parseArray(temporaryData);
        List<String> facilityInspectionSnapIds = new ArrayList<>();
        if (StringUtils.isNotEmpty(temporaryData)&&jsonArray.size() > 0) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String facilityInspectionSnapId = jsonObject.getString("facilityInspectionSnapId");//巡检设备ID
                String inspectionOrderWorkContentId = jsonObject.getString("inspectionOrderWorkContentId");//巡检内容ID
                String result = jsonObject.getString("result");//输入内容
                JSONArray photoArray = jsonObject.getJSONArray("photoPath");//照片路径
                String abnormal = jsonObject.getString("abnormal");//是否异常，true为异常，false正常
                //保存该设备下的当前应用场景
                Long applicationId = StringConverters.ToLong(jsonObject.getString("applicationId"));//当前的应用场景ID
                FacilityInspectionSnap facilityInspectionSnap = facilityInspectionSnapBiz.findModel(StringConverters.ToLong(facilityInspectionSnapId));
                if(facilityInspectionSnap!=null){
                    facilityInspectionSnap.setApplicationScenariosId(applicationId);
                    facilityInspectionSnapBiz.addOrUpdate(facilityInspectionSnap);
                }

                if (!facilityInspectionSnapIds.contains(facilityInspectionSnapId)) {
                    facilityInspectionSnapIds.add(facilityInspectionSnapId);
                }
                InspectionOrderWorkContent inspectionOrderWorkContent = inspectionOrderWorkContentBiz.findModel(StringConverters.ToLong(inspectionOrderWorkContentId));
                if (inspectionOrderWorkContent == null) {
                    continue;
                }
                inspectionOrderWorkContent.setResult(result);
                inspectionOrderWorkContent.setContentPhoto(null);
//                if (StringUtils.isNotBlank(abnormal)) {
//                    inspectionOrderWorkContent.setAbnormal(Boolean.parseBoolean(abnormal));
//                }
                if (photoArray != null && photoArray.size() > 0) {
                    Set<Resource> set = new HashSet<>();
                    for (Object object : photoArray) {
                        Resource resource = resourceBiz.findModel(StringConverters.null2Long(object));
                        resource.setEnterprise(enterprise);
                        resource.setResourceName("巡检照片");
                        resourceBiz.addOrUpdate(resource);
                        set.add(resource);
                    }
                    inspectionOrderWorkContent.setContentPhoto(set);
                }
                if (StringUtils.isNotBlank(result) || photoArray != null) {
                    inspectionOrderWorkContent.setFinishTime(StringConverters.ToDateTime(completeDate));
                }
                inspectionOrderWorkContentBiz.addOrUpdate(inspectionOrderWorkContent);

            }
        }
        //异常备注
        JSONArray remarkArray=JSONArray.parseArray(workRemark);
        if (remarkArray != null && remarkArray.size() > 0) {
            for (int j = 0; j < remarkArray.size(); j++) {
                JSONObject remarkObject=remarkArray.getJSONObject(j);
                String contentId=remarkObject.getString("contentId");
                String question=remarkObject.getString("question");
                String measure=remarkObject.getString("measure");
                String remark=remarkObject.getString("remark");
                String createDate=remarkObject.getString("createDate");
                this.addRemark(contentId,question,measure,remark,StringConverters.ToDateTime(createDate));
            }
        }
        //更新百分比(以及工单是否异常 以及更新inspectionOrder表工时字段)
        this.updatePercent(inspectionOrderId);

        //查询审批信息，并且推送
        List<Long> ids = new ArrayList<>();
        if (inspectionOrder.getAuditCompleteID() != null) {
            JSONArray completeArray = JSONArray.parseArray(inspectionOrder.getCompleteFlow());
            if (completeArray != null && completeArray.size() > 0) {
                inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.IN_AUDITING);
                inspectionOrder.setLevel(1);
                if (completeArray.size() == 1) {
                    inspectionOrder.setAuditLast(true);
                } else {
                    inspectionOrder.setAuditFirst(true);
                }
                inspectionOrder.setAuditing(true);
                JSONObject jsonObject = completeArray.getJSONObject(0);
                Long organizationId = jsonObject.getLong("organizationId");
                Organization organization = organizationBiz.findModel(organizationId);
                inspectionOrder.setOrganization(organization);
                String nodeTypeEnum = jsonObject.getString("nodeTypeEnum");
                Long relationId = jsonObject.getLong("relationId");
                if (nodeTypeEnum.equals("USER")) {
                    SystemUser user = systemUserBiz.findModel(relationId);
                    inspectionOrder.setAuditSystemUser(user);
                    ids.add(user.getId());
                } else {
                    Position position = positionBiz.findModel(relationId);
                    inspectionOrder.setPosition(position);
                    ids.addAll(systemUserBiz.getUserIdsByPosition(relationId.toString(),organizationId.toString(),enterprise.getId()+""));
                }
                ids.add(inspectionOrder.getReceiveUser().getId());//工单人也需要消息推送

                //消息推送
                String content = "巡检单:" + inspectionOrder.getOrderCode() + "已完成,等待审核!";
                planMessageSendBiz.senMsg(inspectionOrder.getId(),"inspection",inspectionOrder.getEnterprise(),ids,content);
            } else {
                inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.COMPLETED);
            }

        } else {
            inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.COMPLETED);
        }
        inspectionOrder.setPercent(100);
//        inspectionOrder.setAbnormal(true);
        this.addOrUpdate(inspectionOrder);
        return ResultUtil.success("巡检单："+inspectionOrder.getOrderCode()+"上传成功");

    }
}
